在Convert.ChangeType或Convert.ToInt32或int.Parse中,是否有任何性能优势
如果你知道你将要转换string为Int32,使用这Convert.ChangeType似乎是一种不明智的方式.我肯定更喜欢其他任何一个电话.
int.Parse和之间的主要区别Convert.ToInt32(x)是Convert.ToInt32(null)返回0,其中as int.Parse(null)将抛出异常.当然,int.Parse还可以让您更好地控制使用何种文化.
我非常怀疑一个在另一个上面有任何性能优势:我希望 Convert.ToInt32调用int.Parse而不是反过来 - 但是没有记录以这种方式工作,并且单个方法调用的命中不太可能是重要的.(无论如何,它可能会被内联.)
private const int maxValue = 1000000;
static void Main(string[] args)
{
string[] strArray = new string[maxValue];
for (int i = 0; i < maxValue; i++)
{
strArray[i] = i.ToString();
}
int[] parsedNums = new int[maxValue];
CalcChangeTypePerf(strArray,parsedNums);
CalcToInt32Perf(strArray, parsedNums);
CalcIntParse(strArray, parsedNums);
}
public static void CalcChangeTypePerf(string[] strArray,int[] parsedArray)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < maxValue; i++)
{
parsedArray[i] = (int)Convert.ChangeType(strArray[i], typeof(int));
}
stopwatch.Stop();
Console.WriteLine("{0} on CalcChangeTypePerf", stopwatch.ElapsedMilliseconds);
}
public static void CalcToInt32Perf(string[] strArray, int[] parsedArray)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < maxValue; i++)
{
parsedArray[i] = Convert.ToInt32(strArray[i]);
}
stopwatch.Stop();
Console.WriteLine("{0} on CalcToInt32Perf", stopwatch.ElapsedMilliseconds);
}
public static void CalcIntParse(string[] strArray, int[] parsedArray)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < maxValue; i++)
{
parsedArray[i] = int.Parse(strArray[i]);
}
stopwatch.Stop();
Console.WriteLine("{0} on CalcIntParse", stopwatch.ElapsedMilliseconds);
}
Run Code Online (Sandbox Code Playgroud)
这个简单的测试结果
266 on CalcChangeTypePerf
167 on CalcToInt32Perf
165 on CalcIntParse
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3482 次 |
| 最近记录: |