Trust Your API (Railo Caching Silliness)
One of the biggest problems rampant amongst developers is ignoring the standard library and writing your own solution to the same problem because we think it’s faster/smarter/better. I know I’m certainly guilty of this thinking too. Unfortunately this is pretty much always a mistake. I recently stressed this issue quite a lot in my Designing Scalable and Creative Algorithms presentation showing how using built in CF features instead of writing your own algorithm (even if theoretically more efficient) often provides significant performance improvements.
A good example I’ve found of this problem is the Railo railo.runtime.op.Constants class in the Railo runtime source. This class contains a cache for java.lang.Integer instances and methods for getting them from primitive values. It also contains named constants for the values up to 10 and creates the values manually up to 99 and puts them in an array. Another method is provided that converts boolean primitive values to java.lang.Boolean instances.
The sentiment behind this class makes sense. It reduces the number of Integer instances that need to be created and reduces the amount of garbage being generated by the program.
The problem here is that both of these methods implement a feature that already exists in the Java API. Moreover since the method is part of the API it’ll likely get compiled to native code much faster.
Had the Railo developers trusted the API (and read the documentation) they would have used Integer.valueOf(int) and Boolean.valueOf(boolean). Both of these standard API methods use a cache, and the Integer cache provided in the standard library caches values from -128 to 127 (as required by the Java Language Specification) providing a much more expansive cache than the 0 to 99 values the Railo developers implemented.
So back to what I said in my presentation: Trust the API: It is Faster!
It should be noted that Railo supports Java 1.4+ and the cache is only present in 1.5+ so using their own cache in Railo does make some sense, but their use of new Integer() instead of Integer.valueOf() and only caching values of 0-99 means you never get the benefit from Java 1.5+
Apparently this has been fixed in bleeding edge Railo, though the source bundle and the SVN repo haven’t been updated. For anyone else who wondered, they keep that source on Git Hub.