开发者

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

I have a simple function called a lot.

Inside this func开发者_如何学编程tion, 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.


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...


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜