another reason to use Dojo: dojo.string.Builder

I work at a pretty magical place. Not only is working with Jot like programming for the “giant data store in the sky”, I get to work on Dojo and do so with an amazing group of folks. Take, for example, the case of dojo.string.Builder.

The basic idea is that instead of doing naive “+=” concatenation of strings, the string builder class should more efficiently manage the creation of huge string variables. In most scripting languages, the way the creation of huge, immutable intermediate variables is by creating an array or list and adding each new fragment to it, eventually join()-ing it to produce the end string. Until this week, dojo.string.Builder did exactly this.

David smelled a rat, though. His experience didn’t match the conventional wisdom. We quickly had a set of tests for comparing the speed of various string creation methods. On JScript (Internet Explorer and WSH), it seems that stringArray.join("") is fastest by a wide margin. Testing showed it to be 10x faster than the “+=” operator in most cases. Interestingly, on Spidermonkey (Mozilla and Firefox) and Rhino the “+=” operator beat array construction/join by 3x. As a result, dojo.string.Builder now picks the fastest variant available for the interpreter your code is running on.

Taken alone, it’s a small thing, but incidents like this make me feel amazingly lucky to be working with the crew that’s contributing to Dojo.

2 Comments

  1. John Christopher
    Posted December 16, 2005 at 7:32 am | Permalink

    So, does the Mozilla based interpreter do something similar to what construction/join does? What makes it so much faster?

  2. Posted December 16, 2005 at 10:36 am | Permalink

    It seems that Spidermoneky special-cases the string add operation, calling js_ConcatStrings() (defined here http://lxr.mozilla.org/seamonkey/source/js/src/jsstr.c#133) instead of the default adder. js\_ConcatStrings interally tries to realloc instead of throwing away the old left-associated string value, thereby skipping the overhead of intermediate string creation. It’s faster than the array.join() hack since it’s implemented in C.

One Trackback

  1. By Java2Script Pacemaker on June 28, 2007 at 7:11 am

    About String in Firefox, IE and Opera

    In round of “String += String” match, Firefox v.s. IE v.s. Opera, and the WINNER is Opera 8.