Efficiency of Java code with primitive types

前端 未结 9 917
遥遥无期
遥遥无期 2021-01-03 12:18

I want to ask which piece of code is more efficient in Java? Code 1:

void f()
{
 for(int i = 0 ; i < 99999;i++)
 {
  for(int j = 0 ; j < 99999;j++)
  {         


        
9条回答
  •  清歌不尽
    2021-01-03 12:46

    There is one more aspect, which is very important about the two different versions:

    While in variant 2 there are only two temporary objects created (i and j), variant 1 will create 100000 objects (1 x i and 999999 x j). Probably your compiler is going to optimize this, but this is something you can´t be sure of. If it doesn´t optimize it, the garbage collection will behave significantly worse.

提交回复
热议问题