ILSpy显示String.IsNullOrEmpty
按照String.Length
执行。但为什么String.IsNullOrEmpty(s)
比s.Length == 0
快?为什么String.IsNullOrEmpty比String.Length更快?
例如,它的5%,在此测试中领先优势:。
var stopwatches = Enumerable.Range(0, 4).Select(_ => new Stopwatch()).ToArray();
var strings = "A,B,,C,DE,F,,G,H,,,,I,J,,K,L,MN,OP,Q,R,STU,V,W,X,Y,Z,".Split(',');
var testers = new Func<string, bool>[] { s => s == String.Empty, s => s.Length == 0, s => String.IsNullOrEmpty(s), s => s == "" };
int count = 0;
for (int i = 0; i < 10000; ++i) {
stopwatches[i % 4].Start();
for (int j = 0; j < 1000; ++j)
count += strings.Count(testers[i % 4]);
stopwatches[i % 4].Stop();
}
(其它基准测试显示了类似的结果这一个最小化的克鲁夫特的我的电脑上运行的效果另外,顺便说一句,测试比较空出来的字符串出来的速度比IsNullOrEmpty
慢13%左右)。
此外,为什么IsNullOrEmpty
只能在x86上更快,而x64上的String.Length
约快9%?
更新:测试设置详细信息:在运行64位Windows 7,英特尔酷睿i5处理器,启用“优化代码”编译的控制台项目上运行的.NET 4.0。但是,“禁止JIT模块负载优化”也已启用(请参阅接受的答案和注释)。
随着优化完全启用,Length
比IsNullOrEmpty
移除了代表和其他开销快约14%,在本次测试:
var strings = "A,B,,C,DE,F,,G,H,,,,I,J,,K,L,MN,OP,Q,R,,STU,V,,W,,X,,,Y,,Z,".Split(',');
int count = 0;
for (uint i = 0; i < 100000000; ++i)
count += strings[i % 32].Length == 0 ? 1 : 0; // Replace Length test with String.IsNullOrEmpty
不知道你所处的确切情况,我相当确信在大多数情况下,还有其他的优化方法让人痛苦,而不是最快的方法来检查一个字符串是否没有任何数据。 – Andrew 2012-04-28 03:41:52
@minitech因为有4个测试人员,他独立计时。 – 2012-04-28 03:46:43
'Empty'和'=='与'Length'和'IsNullOrEmpty'相比如何? – 2012-04-28 03:47:40