Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is calling size() on List or Map in Java?

Tags:

java

How expensive is calling size() on List or Map in Java? or it is better to save size()'s value in a variable if accessed frequently?

like image 372
AppleGrew Avatar asked Oct 28 '10 10:10

AppleGrew


2 Answers

Implement it, then test it. If it is slow, take a closer look.

"Premature optimisation is the root of all evil." - D. Knuth

Also: You should not require certain implementation features, especially if they are black-boxed. What happens if you replace that list with a concurrent list at a later date? What happens if Oracle decides to rewrite List? Will it still be fast? You just don't know.

like image 101
Kajetan Abt Avatar answered Sep 29 '22 14:09

Kajetan Abt


for ArrayList the implementation is like

   public int size() {
       return lastIndex - firstIndex;
   }

So not over head

You can check the source code for detailed info for your required Impl.

Note: The source given is from openjdk

like image 23
jmj Avatar answered Sep 29 '22 15:09

jmj