6

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();
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
Zbarcea Christian
  • 9,367
  • 22
  • 84
  • 137
  • Class member, if memory serves. You can dig through the source code of the various implementations to find out, but I really doubt the iteration approach would be taken. Far too much of a performance penalty to warrant the 4 byte memory savings. Your two loops *can* be equivalent if the sizes don't change, and I *think* that the JITC in that case can turn one into the other. Whether you use `ArrayList` or `List` is a matter of flexibility. In the end, you choose the actual implementation. `size()` and `isEmpty()` solve different problems. – awksp Jun 24 '14 at 17:22
  • What type of `List` does `getCoords()` return? It probably doesn't matter, but it's worth noting that `List` is merely an interface, so implementations of it may behave differently. – Fengyang Wang Jun 24 '14 at 17:23
  • No need to "dig". Check out the source code. As for the ArrayList vs List: One is an interface. Keeping an interface on the left of the assignment has its advantages (more on that somewhere here on SO) – keyser Jun 24 '14 at 17:24

1 Answers1

3

Java List uses a instance variable to handle the size. It is incremented when you add, and decremented when you decrease. Calling list.size() returns a variable, and is therefore O(1).

List.size() would (theoretically) look something like:

public int size() {
    return this.size;
}

Calling List.isEmpty() is a boolean check on whether the instance variable size is equal to 0 or not.

public boolean isEmpty() {
    return (this.size==0);
}

Since this is a instance variable, it doesn't matter (from what I know) what type of List you use, since all inherit a general interface and have the required add() and other functions.

Mike Elofson
  • 2,017
  • 1
  • 10
  • 16