When I write some API, it sometimes will use Collection<Model> to be the parameter. Of course, you can use ArrayList if you know ArrayList is already enough to handle all the use case.
My question is is there any considerable performance cost when for example cast the ArrayList<Model> to Collection<Model> when passing parameter.
Will the collection size also impact the performance of casting? Any advice?
Thanks for Peter’s answer.
I think the answer is pretty enough to stop me to waste time on changing it.
EDIT
As said in accepted answer, the cost is actually paid in the calling of interface methods.
it’s not free to keep this kind of flexibity. But the cost is not so considerable.
Like most performance questions the answer is; write cleare and simple code and the application usually performs okay as well.
A cast to an interface can take around 10 ns (less than a method call) Depending on how the code is optimised, it might be too small to measure.
A cast between generic types is a compiler time check, nothing actually happens at runtime.
When you cast, it is the reference type which changes, all references are the same size. The size of what they point to doesn’t matter.
BTW: All ArrayList objects are the same size, All LinkedList objects are the same size all HashMap objects are the same size etc. They can reference an array which can be different sizes in different collection.
You can see a difference in code which hasn’t been JITed.
prints
however the difference is likely to be due to the method calls being more expensive. The only bytecode difference is
and
Once the JIT has optimised the code there isn’t much difference. Run long enough, the time drops to 0 ns for the -server JVM because it detects the loop doesn’t do anything. 😉