Efficiency of Java code with primitive types

前端 未结 9 754
遥遥无期
遥遥无期 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:31

    Second is better for speed.

    Reason is that in the first case, the scope of j is limited to the inner for loop.

    As such, the moment, the inner loop is completed, the memory for j is de-allocated, and again allocated for the next iteration of the outer loop.

    Because the memory allocation and deallocation take some time, even though it's on stack, the performance of the first one is slower.

提交回复
热议问题