将字符串转换为int.Parse()和Convert.ToInt32()之间的整数值有什么显着的优点吗?
string stringInt = "01234"; int iParse = int.Parse(stringInt); int iConvert = Convert.ToInt32(stringInt);
我发现了一个问题,询问有关转换VS转换,但我认为这是不同的,对不对?
当传递一个字符串作为参数时,Convert.ToInt32在内部调用int.Parse.所以唯一的区别是额外的空检查.
这是.NET Reflector的代码
public static int ToInt32(string value) { if (value == null) { return 0; } return int.Parse(value, CultureInfo.CurrentCulture); }
物有所值:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int iterations = 1000000; string val = "01234"; Console.Write("Run 1: int.Parse() "); DateTime start = DateTime.Now; DoParse(iterations, val); TimeSpan duration = DateTime.Now - start; Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms"); Console.Write("Run 1: Convert.ToInt32() "); start = DateTime.Now; DoConvert(iterations, val); duration = DateTime.Now - start; Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms"); Console.Write("Run 2: int.Parse() "); start = DateTime.Now; DoParse(iterations, val); duration = DateTime.Now - start; Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms"); Console.Write("Run 2: Convert.ToInt32() "); start = DateTime.Now; DoConvert(iterations, val); duration = DateTime.Now - start; Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms"); Console.Write("Run 3: int.Parse() "); start = DateTime.Now; DoParse(iterations, val); duration = DateTime.Now - start; Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms"); Console.Write("Run 3: Convert.ToInt32() "); start = DateTime.Now; DoConvert(iterations, val); duration = DateTime.Now - start; Console.WriteLine("Duration: " + duration.TotalMilliseconds.ToString() + "ms"); Console.ReadKey(); } static void DoParse(int iterations, string val) { int x; for (int i = 0; i < iterations; i++) { x = int.Parse(val); } } static void DoConvert(int iterations, string val) { int x; for (int i = 0; i < iterations; i++) { x = Convert.ToInt32(val); } } } }
每个1,000,000次迭代的结果:
Run 1: int.Parse() Duration: 312.5ms Run 1: Convert.ToInt32() Duration: 328.125ms Run 2: int.Parse() Duration: 296.875ms Run 2: Convert.ToInt32() Duration: 312.5ms Run 3: int.Parse() Duration: 312.5ms Run 3: Convert.ToInt32() Duration: 312.5ms