Tuesday, March 18, 2003

Optimization vs. Readability

Coming from a CIS background, I've never had the same appreciation for low level optimization as co-workers with CS backgrounds. My philosophy has always been: readability is always more important than optimization, unless it's been proven that the specific situation is a bottleneck.

This opinion has never been popular, but it was dismissed almost completely in the early days of Java. Java was always sooo slow, that any optimization helped. Method calls were minimized; string manipulation was reserved for StringBuffers and character arrays; and anything that could be done in native code, was.

At the time, we did what we needed to do. Today, however, many programmers haven't accepted that those days are behind us. Not to say people should start writing slop; but more than ever before, we can trust the VM to do its job.

Consider this code:

StringBuffer buf = new StringBuffer();
buf.append("select table1.columnA, table2.columnB, table3.columnC from ")
.append("someTable table1, someOtherTable table2, table3 where ")
.append("table1.key = table2.key and table2.key = table3.key "
.append("and table1.key=?");
con.prepareStatement(buf.toString);

It could look like this, without any performance penalty:

String sql =
"select table1.columnA, table2.columnB, table3.columnC from " +
"someTable table1, someOtherTable table2, table3 where "
"table1.key = table2.key and table2.key = table3.key "
"and table1.key=?";
con.prepareStatement(sql);

Not only is the direct use of strings easier to read, it's use is optimized in many IDEs (IDEA automatically places ["+"] in a string when you press enter in a string. Ctrl-J will concatenate strings from separate rows.).

Many programmers (especially those who suffered through the early version of the Java VM), still cache objects unnecessarily, rather than relying on garbage collection. Many implement all their Swing listeners in a single class and perform their own event delegation to save on class creation. My personal favorite is parsing Strings as character arrays, which of course renders the code completely unreadable while (according to an article in Oct 2002 Java Pro - "How Hot is HotSpot?") actually slows the code down in a modern VM. You read that right! In some cases, the code that was optimized for older VMs is now slower than more readable code.

One more thing to consider when optimizing that code: What costs your company more? people or machines? If your optimizing a problem that will improve the client's perception of the product, then go right ahead. If your making the code less readable because "it's theoretically faster this way", make sure the theory is true, and the change is worth it's time in readability.

Labels:

0 Comments:

Post a Comment



<< Home