patternjavaMinor
Which is better for checking previous object in list?
Viewed 0 times
previouscheckingbetterforwhichlistobject
Problem
I have a for loop which loops through a list and builds and object, I needed to check the previous object with the one i'm building...which way is better?
This way?:
Or This way?:
I can see how one looks better than the other...but which one would be more efficient?
This way?:
String lastDirection= "";
List stages = new ArrayList();
for (Object object : results) {
Vector result = (Vector) object;
Stages stage = new Stages();
stage.setStage(result.get(0).toString());
stage.setDirection((String) result.get(1));
stage.setStageName((String) result.get(2));
if(!stage.getDirection.equals(lastDirection))
stages.add(stage);
lastAtco = stage.getDirection();
}
return stages;Or This way?:
List stages = new ArrayList();
for (Object object : results) {
Vector result = (Vector) object;
Stages stage = new Stages();
stage.setStage(result.get(0).toString());
stage.setDirection((String) result.get(1));
stage.setStageName((String) result.get(2));
if (stages.size() >= 1 && stages.get(stages.size() - 1).getDirection().equals(stage.getDirection())) {
} else {
stages.add(stage);
}
}
return stages;I can see how one looks better than the other...but which one would be more efficient?
Solution
The former would definitely be more efficient.
In the latter case, you "forget" a local variable that you have available (by letting it go out of scope), and then on the next iteration get it back by calling
In the latter case, you "forget" a local variable that you have available (by letting it go out of scope), and then on the next iteration get it back by calling
stages.get(). There's no way that the get() call will be as cheap as simply referencing the lastDirection variable.Context
StackExchange Code Review Q#17885, answer score: 5
Revisions (0)
No revisions yet.