Why does C# execute Math.Sqrt() more slowly than VB.NET?

后端 未结 6 1560
情深已故
情深已故 2020-12-14 05:45

Background

While running benchmark tests this morning, my colleagues and I discovered some strange things concerning performance of C# code vs. VB.NET code.

6条回答
  •  悲&欢浪女
    2020-12-14 06:13

    I agree with the statement that the C# code is computing sqrt on every iteration and here is the proof straight out of Reflector:

    VB version:

    private static void testIfPrimeSerial(int suspectPrime)
    {
        int VB$t_i4$L0 = (int) Math.Round(Math.Sqrt((double) suspectPrime));
        for (int i = 2; i <= VB$t_i4$L0; i++)
        {
            if ((suspectPrime % i) == 0)
            {
                return;
            }
        }
        temp.Add(suspectPrime);
    }
    

    C# version:

     private void testIfPrimeSerial(int suspectPrime)
    {
        for (int i = 2; i <= Math.Sqrt((double) suspectPrime); i++)
        {
            if ((suspectPrime % i) == 0)
            {
                return;
            }
        }
        this.temp.Add(suspectPrime);
    }
    

    Which kinda points to VB generating code that performs better even if the developer is naive enough to have the call to sqrt in the loop definition.

提交回复
热议问题