Efficiency of Java code with primitive types

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

    I would guess that there is absolutely no difference in efficiency for any half-decent JVM implementation.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 12:47

    The second is worse.

    Why? Because the loop variable is scoped outside the loop. i and j will have a value after the loop is done. Generally that isn't what you want. The first scopes the loop variables so it's only visible within the loop.

    0 讨论(0)
提交回复
热议问题