Why is 2 * (i * i) faster than 2 * i * i in Java?

前端 未结 10 730
一生所求
一生所求 2020-12-22 14:43

The following Java program takes on average between 0.50 secs and 0.55 secs to run:

public static void main(String[] args) {
    long startTime = System.nano         


        
10条回答
  •  青春惊慌失措
    2020-12-22 14:57

    While not directly related to the question's environment, just for the curiosity, I did the same test on .NET Core 2.1, x64, release mode.

    Here is the interesting result, confirming similar phonomena (other way around) happening over the dark side of the force. Code:

    static void Main(string[] args)
    {
        Stopwatch watch = new Stopwatch();
    
        Console.WriteLine("2 * (i * i)");
    
        for (int a = 0; a < 10; a++)
        {
            int n = 0;
    
            watch.Restart();
    
            for (int i = 0; i < 1000000000; i++)
            {
                n += 2 * (i * i);
            }
    
            watch.Stop();
    
            Console.WriteLine($"result:{n}, {watch.ElapsedMilliseconds} ms");
        }
    
        Console.WriteLine();
        Console.WriteLine("2 * i * i");
    
        for (int a = 0; a < 10; a++)
        {
            int n = 0;
    
            watch.Restart();
    
            for (int i = 0; i < 1000000000; i++)
            {
                n += 2 * i * i;
            }
    
            watch.Stop();
    
            Console.WriteLine($"result:{n}, {watch.ElapsedMilliseconds}ms");
        }
    }
    

    Result:

    2 * (i * i)

    • result:119860736, 438 ms
    • result:119860736, 433 ms
    • result:119860736, 437 ms
    • result:119860736, 435 ms
    • result:119860736, 436 ms
    • result:119860736, 435 ms
    • result:119860736, 435 ms
    • result:119860736, 439 ms
    • result:119860736, 436 ms
    • result:119860736, 437 ms

    2 * i * i

    • result:119860736, 417 ms
    • result:119860736, 417 ms
    • result:119860736, 417 ms
    • result:119860736, 418 ms
    • result:119860736, 418 ms
    • result:119860736, 417 ms
    • result:119860736, 418 ms
    • result:119860736, 416 ms
    • result:119860736, 417 ms
    • result:119860736, 418 ms

提交回复
热议问题