0

Is the size() method the ArrayList class simply a getter, or does it perform any sort of calculation?

If it is a getter then is it safe to assume that it will be inlined at some point if I call it a large number of times?

Acidic
  • 6,154
  • 12
  • 46
  • 80

5 Answers5

2

If you're asking if there's any overhead in calling "size()", the answer is "No".

Here's a similar discussion on a similar method, String.length():

In Java, for a string x, what is the runtime cost of s.length()? Is it O(1) or O(n)?

The answer in both cases - String.length() and ArrayList.size() - is "O(1)".

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
1

size() method is not a standard setter/getter, it is a method of List which is defined to give the size of the list (number of elements)

ArrayList implements it by following way

 public int size() {
  230           return size;
  231       }

it maintains a int variable called size, when we add it increases, decreases on removal.

jmj
  • 237,923
  • 42
  • 401
  • 438
1

Whether or not ArrayList.size() will ever be inlined depends on a number of factors, but, yes, at least in theory if you reference size() enough times and if all the other inlining criteria are met then it will be inlined.

For the most part ArrayList is just a class, not unlike a class that you might write. So it would be subject to the same inlining rules/potential.

[Just checked the source for ArrayList and here is what I found:

public int size() {
    return size;
}

Which is about as vanilla (and highly inline-able) as you can get. So I'd say that size() will inline in virtually all cases where you don't seriously obscure the class type somehow.]

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
1

If you wish to truly see for yourself how the size() method is implemented, you may download the source for the java library as it is under the GNU GPL; line 196 in the OpenJDK 6 sources.

OpenJDK 7 Sources

On the topic of inlining, you may wish to read the following post:

Inlining in Java

Community
  • 1
  • 1
V_P
  • 111
  • 3
0

Since the getter is just returning a a field, there is no negative performance impact. The JIT is smart enough to inline the call so that you dont have the function call overhead.

See similar question here: Is ArrayList.size() method cached?

Community
  • 1
  • 1
Deco
  • 3,261
  • 17
  • 25