Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is optimal?

Is declaring a variable inside a loop is good or declaring on the fly optimal in Java.Also is there any performance cost involved while declaring inside the loop?

eg.

Option 1: Outside the Loop

List list = new ArrayList();
int value;

//populate list
for(int i = 0 ; i < list.size(); i++) {
  value = list.get(i);
  System.out.println(“value is ”+ value);
}

Option 2: Inside the Loop

List list = new ArrayList();

//populate list
for(int i = 0; i < list.size(); i++) {
  int value = list.get(i);
  System.out.println(“value is ”+ value);
}
like image 896
Harish Avatar asked Dec 10 '22 18:12

Harish


2 Answers

In Clean Code, Robert C. Martin advises Java coders to declare variables as close as possible to where they are to be used. Variables should not have greater scope than necessary. Having the declaration of a variable close to where it's used helps give the reader type and initialization information. Don't concern yourself too much with performance because the JVM is pretty good at optimizing these things. Instead focus on readability.

BTW: If you're using Java 5 or greater, you can significantly trim up your code example using the following new-for-Java-5 features:

  • foreach construct
  • generics
  • autoboxing

I've refactored your example to use the aforementioned new features.

List<Integer> list = new ArrayList<Integer>();

// populate list

for (int value : list) {
    System.out.println("value is " + value);
}
like image 163
Asaph Avatar answered Dec 21 '22 23:12

Asaph


It should make no difference which way you implement from a performance perspective.

But more importantly, you should not be wasting your time micro-optimizing your code like this ... UNLESS you've profiled your entire application and determined that this fragment is a performance bottleneck. (And if you've done that, you are in a good position to see if there is really any difference between the two versions of the code. But I would be very, surprised if there was ...)

like image 36
Stephen C Avatar answered Dec 22 '22 01:12

Stephen C