Posts

Showing posts with the label Collections

Get a feel for what your computer can do

When examining performance with an eye to optimization, it's worth developing a feel for how fast typical software operations actually are on modern hardware. That sense will help you know when to look deeper for the real cause of a bottleneck, or when to look elsewhere, or when to mistrust the results that your profiling tools are giving you. For instance, I ran the following short bit of code: TreeSet tree = new TreeSet (); int found = 0; long time = System.currentTimeMillis(); System.out.println("add #'s to tree"); for (int i = 0; i long time2 = System.currentTimeMillis(); System.out.println("elapsed:  " + (time2 - time)); System.out.println("find #'s in tree"); for (int i = 0; i     if (tree.contains(Math.random())) found++; long time3 = System.currentTimeMillis(); System.out.println("elapsed:  " + (time3 - time2)); Here's the output: add #'s to tree elapsed: 8240 find #'s in tree elapsed: 5476 We see that filling a J...

Use Parent/Interface types rather than implementation types

If you've got a method that returns, say, a  TreeMap  pointer, you can generally declare it to return a  Map ; you're unlikely to use a method of TreeMap  that isn't a method of  Map  (if there even are such things), so the calling code won't be affected. This allows you, though, to change the implementation class to, say,  HashMap  without any other code being affected. The same goes for parameters passed into a method. In general, only explicitly use the implementation type when creating the instance [i.e. new ()]. [ NOTE : There's an issue peculiar to C++ where one must make sure that the implementation class' destructor is virtual, or it won't be executed when one deletes a pointer of the parent-class type.]

The use of Java Sets

The Set interface requires that the underlying implementation can tell whether two objects added to it are the same, so that the second can be rejected (a Set is defined as only containing one copy of any given object).  Ensuring adherence to this requirement involves both the Set implementation and the mechanism by which the objects can be distinguished from one-another.  The two basic implementations that i use in my code, TreeSet and HashSet , handle this in different ways: TreeSets are ordered b-trees (or something very similar) of objects.  Because they’re ordered, the objects they contain must implement the Comparable interface, or alternatively the TreeSet itself may have a Comparator member; in either case, a compareTo () method is called to compare objects to one another.  compareTo () returns -1, 0 or 1, depending on whether the first argument is less than, equal to or greater than the second; this is how the nodes in the tree are ordered, and how the Tre...