Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ArrayList.size() method cached?

I was wondering, is the size() method that you can call on a existing ArrayList<T> cached? Or is it preferable in performance critical code that I just store the size() in a local int?

I would expect that it is indeed cached, when you don't add/remove items between calls to size().

Am I right?

update
I am not talking about inlining or such things. I just want to know if the method size() itself caches the value internally, or that it dynamically computes every time when called.

like image 561
Peterdk Avatar asked May 18 '10 11:05

Peterdk


1 Answers

I don't think I'd say it's "cached" as such - but it's just stored in a field, so it's fast enough to call frequently.

The Sun JDK implementation of size() is just:

public int size() {
    return size;
}
like image 182
Jon Skeet Avatar answered Sep 28 '22 09:09

Jon Skeet