As I had already mentioned in the last post, I found three different scripts for date formatting and profiled them (if you haven’t read it, do that first). Finally I went with the one that uses eval, because it is the fastest. Here’s why:
It builds a function that is tailored to the exact pattern, assuming of course that the same pattern is used more than once (which in this case is true), and uses eval to compile that function. Then it stores it in a hash under the pattern. The next time when that pattern comes around, all that is needed is a hash lookup – which is wickedly fast – to find and execute the function. Since this approach does need to scan the pattern every time it can theoretically achieve O(1) performance (for static patterns that is)!!! This is not true for the other two algorithms since they both need to scan the pattern in its entirety every time.
To get rid of the eval, I briefly thought of using a similar approach of maybe storing the bits of the scanned pattern in a list that works sorta like a trie: Static parts are thrown together and only make up one element in the list. Dynamic elements that need to be evaluated using the Date that was passed in are stored as functions that get called. At least this way it might still be able to achieve O(1) performance for static patterns. I later discarded that approach since the second fastest algo was only slightly slower for 1000 iterations — and went with scanning the pattern every time. I just had to change the code that returns the strings to make up the final function to actually execute that code.
For parsing a date-string into a Date object the original code also used eval in the same vein, of course using a regex to do the actual parsing. In that case I figured that I could parse the pattern the first time around, build a regex object and cache it for later use. Then I need to still scan the pattern though to find the right code to execute for each piece, each match that is.
At the end of the day, the difference in TB is not noticeable, probably barely even slower. I will see if I can find a way to profile it inside TB (Venkman was not really working and there is sadly no firebug for TB – any takers :?)
Well, the whole point of this story was to say that I left the original date-formatting code in TBTracer, in case anybody wants to go back to the faster code (without telling mozilla – that is only between you and me 😉 In the TBT extension folder (Mac’s as an example can be found at ~Library/Thunderbird/Profiles/<profile-id>/extensions/TBTracer@derdoc.info/) under /chrome/content there is a file named date.js and one named date.js.old. Just swap the two, restart TB, and voilà you have the faster code!