为什么ToUpper比ToLower快?

Med*_*edo 4 .net c#

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);
Run Code Online (Sandbox Code Playgroud)

我跑了很多次:

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
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 6

让我们尝试重现结果

  // Please, notice: the same string for both ToUpper/ToLower
  string GiniPig = string.Concat(Enumerable
    .Range(1, 1000000) // a million chunks "my test/MyTest" combined (long string)
    .Select(item => "my test/MY TEST"));

   Stopwatch sw = new Stopwatch();

   // Let's try n (100) times - not just once
   int n = 100;

   var sampling = Enumerable
     .Range(1, n)
     .Select(x => {
        sw.Reset();
        sw.Start();

        GiniPig.ToLower(); // change this into .ToUpper();

        sw.Stop();
        return sw.ElapsedMilliseconds; })
     .ToSampling(x => x); // Side library; by you may save the data and analyze it with R

   Console.Write(
     $"N = {n}; mean = {sampling.Mean:F0}; std err = {sampling.StandardDeviation:F0}");
Run Code Online (Sandbox Code Playgroud)

运行了几次(变暖)我得到了结果(Core i7 3.6 GHz,.Net 4.6 IA-64):

ToLower: N = 100; mean = 38; std err = 8
ToUpper: N = 100; mean = 37; std err = 9
Run Code Online (Sandbox Code Playgroud)

所以你不能拒绝ToLower那么快的假设,ToUpper因此你的实验有错误:

  1. 您有不同的字符串要处理
  2. 处理(175仅字符)字符串只需一次(不在循环中)应该是即时的,因此错误可能是极其重要的
  3. 你必须预热例程(为了编译方法,加载程序集,填充缓存等)

似乎(经过的时间超过1秒,非常简单的操作)它的规则#3(预热)破坏了破坏了实验

  • @Medo Medo:`65`和`122`都是以太*单*`char`或*单*`字节`; 这就是为什么时间(在您的示例中)相同的原因(CPU不能使用* digits *来运行,而是使用byte,int,long等等)。 (2认同)