检查字符串首字母的性能
今天在写一个函数的时候,需要判断某段字符串是xml还是数字,一开始用StartsWith来判断开头的字符串,后来发现这个函数需要高频率的调用,不知道StartsWith是否有性能问题。于是写了如下代码来验证:
var content = "<double>1</double>"; Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < 1000000; i++) { var r = content.StartsWith("<"); } sw.Stop(); Console.WriteLine("test 1 :" + sw.ElapsedMilliseconds); sw = Stopwatch.StartNew(); for (int i = 0; i < 1000000; i++) { var r = content.StartsWith("<double>"); } sw.Stop(); Console.WriteLine("test 2 :" + sw.ElapsedMilliseconds); sw = Stopwatch.StartNew(); for (int i = 0; i < 1000000; i++) { var r = content[0] == '<'; } sw.Stop(); Console.WriteLine("test 3 :" + sw.ElapsedMilliseconds);
基本上第三种性能是最高的,不过第二种要保险一些。