The moose likes Performance and the fly likes Optimization? Collection vs. ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "Optimization? Collection vs. ArrayList" Watch "Optimization? Collection vs. ArrayList" New topic

Optimization? Collection vs. ArrayList

Thurston Moore

Joined: Nov 29, 2004
Posts: 2
Would the following:

Collection c = new ArrayList();

be considered an optimization over:

ArrayList a = new ArrayList();

Would the variable c take up less memory than a?

Thank you.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


Welcome to JavaRanch!

There are two important Laws that govern optimization:

1) Don't do it.
2) Don't do it yet.

Small "microoptimizations" like this are a waste of your valuable time to consider. If over a billion executions you could measure a 0.5% speedup on one JVM, you might measure a 0.5% slowdown on another. There are, in fact, good reasons to sometimes use a Collection variable rather than an ArrayList -- but they're design reasons, not performance reasons.

Now regarding the space: all Java object reference variables take up exactly the same amount of space. Please take a few minutes and read this.

[Jess in Action][AskingGoodQuestions]
Stephen Bloch
Ranch Hand

Joined: Aug 19, 2003
Posts: 48
In a sense, declaring the thing as a Collection is an optimization over declaring it as an ArrayList, but it's an optimization for programmer time, not processor time. To wit, declaring the thing as a Collection forces you to use only the interface of Collection on it, so if at some time in the future you decide to change the implementation to something other than ArrayList, you can do it by changing one line of code.

SCJP 1.4
I agree. Here's the link:
subject: Optimization? Collection vs. ArrayList
It's not a secret anymore!