Ternary operator is twice as slow as an if-else block?

后端 未结 10 985
无人及你
无人及你 2020-11-30 16:20

I read everywhere that ternary operator is supposed to be faster than, or at least the same as, its equivalent if-else block.

However, I di

10条回答
  •  被撕碎了的回忆
    2020-11-30 16:44

    Run without debugging ctrl+F5 it seems the debugger slows down both ifs and ternary significantly but it seems it slows down the ternary operator much more.

    When I run the following code here are my results. I think the small millisecond difference is caused by the compiler optimizing the max=max and removing it but is probably not making that optimization for the ternary operator. If someone could check the assembly and confirm this it would be awesome.

    --Run #1--
    Type   | Milliseconds
    Ternary 706
    If     704
    %: .9972
    --Run #2--
    Type   | Milliseconds
    Ternary 707
    If     704
    %: .9958
    --Run #3--
    Type   | Milliseconds
    Ternary 706
    If     704
    %: .9972
    

    Code

      for (int t = 1; t != 10; t++)
            {
                var s = new System.Diagnostics.Stopwatch();
                var r = new Random(123456789);   //r
                int[] randomSet = new int[1000]; //a
                for (int i = 0; i < 1000; i++)   //n
                    randomSet[i] = r.Next();     //dom
                long _ternary = 0; //store
                long _if = 0;      //time
                int max = 0; //result
                s.Start();
                for (int q = 0; q < 1000000; q++)
                {
                    for (int i = 0; i < 1000; i++)
                        max = max > randomSet[i] ? max : randomSet[i];
                }
                s.Stop();
                _ternary = s.ElapsedMilliseconds;
                max = 0;
                s = new System.Diagnostics.Stopwatch();
                s.Start();
                for (int q = 0; q < 1000000; q++)
                {
                    for (int i = 0; i < 1000; i++)
                        if (max > randomSet[i])
                            max = max; // I think the compiler may remove this but not for the ternary causing the speed difference.
                        else
                            max = randomSet[i];
                }
    
                s.Stop();
                _if = s.ElapsedMilliseconds;
                Console.WriteLine("--Run #" + t+"--");
                Console.WriteLine("Type   | Milliseconds\nTernary {0}\nIf     {1}\n%: {2}", _ternary, _if,((decimal)_if/(decimal)_ternary).ToString("#.####"));
            }
    

提交回复
热议问题