Java code efficiency with primitive types

I want to ask, what part of the code is more efficient in Java? Code 1:

void f()
{
 for(int i = 0 ; i < 99999;i++)
 {
  for(int j = 0 ; j < 99999;j++)
  {
   //Some operations
  }
 }

}

Code 2:

void f()
{
 int i,j;
 for(i = 0 ; i < 99999;i++)
 {
  for(j = 0 ; j < 99999;j++)
  {
   //Some operations
  }
 }

}

My teacher said that the second is better, but I can not agree with this opinion.

+2
source share
9 answers

I would prefer the first after the second, because it keeps the loop variables from the path of the rest of the code in the method. Since they are not visible outside the loop, you cannot accidentally refer to them later.

: . do , , . , -.

Java ( Java). Java , . .

, , . : f1 f2 :

$ cat f1.java
public class f1 {
  void f() {
    for(int i = 0 ; i < 99999;i++) {
      for(int j = 0 ; j < 99999;j++) {
      }
    }
  }
}

$ cat f2.java
public class f2 {
  void f() {
    int i, j;
    for(i = 0 ; i < 99999;i++) {
      for(j = 0 ; j < 99999;j++) {
      }
    }
  }
}

:

$ javac f1.java
$ javac f2.java

:

$ javap -c f1 > f1decomp
$ javap -c f2 > f2decomp

:

$ diff f1decomp f2decomp
1,3c1,3
< Compiled from "f1.java"
< public class f1 extends java.lang.Object{
< public f1();
---
> Compiled from "f2.java"
> public class f2 extends java.lang.Object{
> public f2();

- .

+17

IT. . . A. .

. .

.

, , , , , .

+31

-!!!

, 10 . :

50, 3, 
3, 0, 
0, 0, 
0, 0, 
....

- , . , , javac.

1: , "". , , . , , .

, if (i < 2 * j) longK++; longK. :

32267, 33382,
34542, 30136,
12893, 12900,
12897, 12889,
12904, 12891,
12880, 12891,
....

, , , . JVM ( ) . ( ), , . , JIT. , , . - .

2: JVM. , , .

- , JVM , .

+13

.

? . i j . , , . , .

+6

, JVM.

+2

, ( ). . , MasterGaurav.

JVM , .

( ) , , j, . , JVM (, )

+2

, , , . ? , , . , 2 - -, ( ), .

0

-, .

, j for.

, , , j .

, , .

-4

, :

2 (i j), 1 100000 (1 x 999999 x j). , , , . , .

-4
source

Source: https://habr.com/ru/post/1746938/


All Articles