Best practice in `For` loop in java

Possible duplicate:
to optimize the cycle

In java, I have a code block:

List e = {element1, element2, ...., elementn};
for(int i = 0; i < e.size(); i++){//Do something in here
};

and one more block:

List e = {element1, element2, ...., elementn};
int listSize = e.size();
for(int i = 0; i < listSize; i++){//Do something in here
};

I think the second block is better, because in the first block, if i++, we need to calculate e.size()again to compare the condition in the loop for. Right or wrong? And comparing the two blocks above, what is the best way to write? And why? Explain clearly and try this cycle yourself.

+3
source share
12 answers

Personally, I would use the for statement:

for (Object element : e) {
    // Use element
}

Unless you need an index, of course.

, , ( , ), , . ( e.size() - , JIT .)

+14

- , . Java ( , Iterable) - .

for (Object object : someCollection) { // do something }

, , . , , JIT , .

: , " - "? .

+6

size() LinkedList, , , . size() - .
size() , .

+4

( ):

List e = {element1, element2, ...., elementn};
for(int i = 0, size = e.size(); i < size; i++){
    // Do something in here
};

e.size() .

, for. .

a

for (MyClass myObj : list) {
    // Do something here
}

, ( Iterator).

+2

, , size(). ​​.

, . . .

+1

HotSpot e.size() . .

, :

for (Object elem: e) {
   //Do something
}
+1

, . int , .

List e = {element1, element2, ...., elementn};
int listSize = e.size();
int i=0;
for(i = 0; i < listSize; i++){//Do something in here
};
+1

, , java , .

0

, e.size() - , , JVM.

0

, . ( )

for (Object object : aCollection) { 
// Do something here
}

, : :
- , , .

0

, , .

0

the second is better, cos in the firt loop in her body, maybe you will make this expression e.remove, and then the size of e will be changed, so it’s better to save the size in the parameter before looop

-1
source

All Articles