Home > JavaScript > Process String

Process String

My good friend Mauvis was writing on his blog about to convert a string to comma separated ascii numbers. I commented there about his code. Here’s how I wrote, and also see his original: String.toCharCode().

String.prototype.toCharCode = function()
{
  var str = this.split('');
  var len = str.length;
  var work = new Array(len);
  for (var i = 0; i < len; ++i)
  {
    work[i] = String.charCodeAt(str[i]);
  }
  return work.join(',');
}

It was his quick hack for the day, I suppose, but it turns out to be very interesting thing to me. There are a few points to write faster code.

  1. explicit length of for loop — dot access considered harmful at least for speed.
    for JavaScript, .(dot) access is always very slow. Some people do like… for (var i = 0; i < arr.length; i++). That’s not good. On this case, i need to use array length twice so I made a local variable. The local variables are always the fastest access.
  2. NO for…in for Array
    for…in is basically built for Object enumeration. By using for…in, JavaScript will pass all properties with the internal DontEnum attribute false, to i (or accessor whatever you name). MDC:Object.propertyIsEnumerable() is very interesting to read about this topic.
  3. Do not concatenate a string
    In most of languages, string is immutable. In my early life of programming, I always wondered.. what’s the hell? Immutable? As its meaning, string is not changeable. but let’s see like…
    var s = "foo";
    s = "bar";
    alert(s); // returns "bar"!

    right? You can change it. But as a lower process level point of view, the code above is same exact meaning as follows.

    var s = new String("foo");
    s = new String("bar");
    alert(s); // returns "bar"!

    Two instantiation process. Now you believe me, right? This article: HotRubyがC Rubyより速い本当の理由は? (written in Japanese) explains very comprehensively how JavaScript engine would implement it. At least you should take a look at this picture. But overall, String concatenation considered harmful. In most cases, you can use Array.join() to connect multiple strings.

These looks very minor and small changes. But it does make a difference.

Comments:0

Comment Form
Remember personal info

Trackbacks:1

Trackback URL for this entry
http://blog.nydd.org/2008/10/28/process-string/trackback/
Listed below are links to weblogs that reference
Process String from Ten Eyck
pingback from ReadyState4 » Blog Archive » String.toCharCode 08-10-28 (Tue) 1:13

[...] version from my good friend Takashi and link to his blog on why it’s more efficient: String.prototype.toCharCode = function(){ var str = this.split(”), len = [...]

Home > JavaScript > Process String

Search
Feeds
Meta
Links

Return to page top