Touloudou
Touloudou

Reputation: 2223

Performance penalty if going through Java base class?

I want to use a Collection whose type is known at compile time (ArrayList). Is there any penalty going through the parent class interface?

Collection<Integer> v = new ArrayList<>();
v.add(42);

versus

ArrayList<Integer> v = new ArrayList<>();
v.add(42);

In C++, the first case would result in a virtual function call, but not the second one. Is it the same in Java?

Upvotes: 0

Views: 60

Answers (2)

VGR
VGR

Reputation: 44308

No, there is no penalty. Your ArrayList is exactly the same object, with exactly the same type. In fact, referring to it as a Collection is a good object-oriented practice, since you are referring to the object by its contract rather than its implementation.

Upvotes: 0

OhleC
OhleC

Reputation: 2890

Java uses dynamic binding for all method calls, so there is no difference (they're equally bad if you will, with the caveat that JIT optimizations will probably make them equally good).

Upvotes: 1

Related Questions