modern for loop for primitive array

前端 未结 5 1996
慢半拍i
慢半拍i 2021-02-05 16:39

Is there any performance difference between the for loops on a primitive array?

Assume:

double[] doubleArray = new double[300000];


for (double var: do         


        
5条回答
  •  独厮守ぢ
    2021-02-05 17:09

    My opinion is that you don't know and shouldn't guess. Trying to outsmart compilers these days is fruitless.

    There have been times people learned "Patterns" that seemed to optimize some operation, but in the next version of Java those patterns were actually slower.

    Always write it as clear as you possibly can and don't worry about optimization until you actually have some user spec in your hand and are failing to meet some requirement, and even then be very careful to run before and after tests to ensure that your "fix" actually improved it enough to make that requirement pass.

    The compiler can do some amazing things that would really blow your socks off, and even if you make some test that iterates over some large range, it may perform completely differently if you have a smaller range or change what happens inside the loop.

    Just in time compiling means it can occasionally outperform C, and there is no reason it can't outperform static assembly language in some cases (assembly can't determine beforehand that a call isn't required, Java can at times do just that.

    To sum it up: the most value you can put into your code is to write it to be readable.

提交回复
热议问题