【发布时间】:2017-05-05 10:11:05
【问题描述】:
Stopwatch stopwatch1 = new Stopwatch();
Stopwatch stopwatch2 = new Stopwatch();
string l = "my test";
string u = "MY TEST";
for (int i = 0; i < 25; i++)
{
l += l;
u += u;
}
stopwatch1.Start();
l=l.ToUpper();
stopwatch1.Stop();
stopwatch2.Start();
u=u.ToLower();
stopwatch2.Stop();
// Write result.
Console.WriteLine("Time elapsed: \nUPPER : {0}\n LOWER : {1}",
stopwatch1.Elapsed, stopwatch2.Elapsed);
我跑了很多次:
UPPER : 00:00:01.3386287
LOWER : 00:00:01.4546552
UPPER : 00:00:01.1614189
LOWER : 00:00:01.1970368
UPPER : 00:00:01.2697430
LOWER : 00:00:01.3460950
UPPER : 00:00:01.2256813
LOWER : 00:00:01.3075738
【问题讨论】:
-
首先,您应该为多次转换计时!试试 10000
-
并尝试颠倒顺序以消除缓存影响
-
您应该使用 ToUpperInvariant 和 ToLowerInvariant。并且您使用 BenchmarkDotNet 进行测试。
-
This might be the answer you are looking for。 “在规范化字符串时,强烈建议您使用 ToUpperInvariant 而不是 ToLowerInvariant,因为 Microsoft 已经优化了执行大写比较的代码。”