Matthieu Napoli
Matthieu Napoli

Reputation: 49583

Use list.size() or a variable for multiple use ? (local optimization)

I have a simple function called a lot.

Inside this function, I have many calls to the size of a list (containing around 10 elements):

list.size()

Is it faster for me to use a temporary variable to get the size only once, or is it faster to call the size() method every time?

Update: it's an ArrayList.

Note: I know what I am doing, I am not looking for a lecture regarding optimization and how it should or shouldn't be done. I am just looking for an answer.

Upvotes: 4

Views: 658

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1501033

It entirely depends on the implementation. You haven't specified the type of list - I assume it's a List<E> or some concrete implementation.

In some implementations such as ArrayList<E> it's extremely cheap - a field access, basically. It's only documented in terms of being constant time, admittedly:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.

In others it could potentially be expensive. The interface doesn't provide any guarantees. I would expect it to be cheap (constant time) in most implementations, but you never know for sure...

Upvotes: 10

dhblah
dhblah

Reputation: 10151

Regardless of how fast size() method call is. It's a good practice to introduce a variable to carry the result of the method, if that method is invoked multiple times inside a block of code, assuming that the method doesn't change anything.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240908

It depends on implementation of the List Looking at the ArrayList's source

/**
  225        * Returns the number of elements in this list.
  226        *
  227        * @return the number of elements in this list
  228        */
  229       public int size() {
  230           return size;
  231       }
  232   

So it doesn't matter if you take a local variable or call this method

Upvotes: 7

Lukas Eder
Lukas Eder

Reputation: 220952

Check this out (from ArrayList and also LinkedList):

/**
 * Returns the number of elements in this list.
 *
 * @return the number of elements in this list
 */
public int size() {
return size;
}

Calling list.size() is about as efficient as invoking a method and putting a value on the stack: (almost) negligible. Of course you'll be a tiny bit faster using a local (final) variable. If this is an important improvement in the context of your application or not, you will probably have to measure.

Upvotes: 4

Related Questions