I want to know the performance of .size()
method. Does this method returns a reference from the number of objects in the list (like a class member which is incremented every time when an object is added to the list)? Or does it iterate through all objects?
Which one is more efficient?
Calling .size()
every time:
List<Vector3> objects = getCoords();
for (int x = 0; x < objects.size(); x++){
for (int y = 0; y < objects.size(); y++){
for (int z = 0; z < objects.size(); z++){
drawShape(x, y, z);
}
}
}
Or by saving to a local variable:
List<Vector3> objects = getCoords();
int size = objects.size();
for (int x = 0; x < size; x++){
for (int y = 0; y < size; y++){
for (int z = 0; z < size; z++){
drawShape(x, y, z);
}
}
}
Let's assume that we have > 30.000 objects in the list.
Which one is more faster/efficient?
Does it matter if we use an ArrayList<T>
or a List<T>
?
What about simple statements: .size()
or .isEmpty()
if (objects != null && objects.size() > 0){
doThis();
}
or by calling .isEmpty()
if (objects != null && !objects.isEmpty()){
doSomethingElse();
}