Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Optimization? Collection vs. ArrayList

 
Thurston Moore
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.
 
Stephen Bloch
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic