Hi-performance Javascript Tips #2

Create your own version of Java’s StringBuilder:

var StringBuilder = function (str) {
    var _stack = str ? [str] : []; // str == initial string to start, if any
    // append can take one or more strings as arguments
    this.append = function () {
        _stack.push.apply(_stack, arguments);
        return this;
    this.toString = function (separator) {
        return _stack.join(separator || '');

This routine runs up to 8x faster in IE6 than normal string concatenation using the + and += operators! In IE7, I’ve clocked a 4x improvement.

Firefox 3.0 gets about a 20% speed boost. Safari 4 and Chrome get less than a 10% speed boost.

It would be an easy exercise to modify the StringBuilder class’ append method and constructor to take an existing StringBuilder object instead of a string.

Hi-performance Javascript Tips #1 [Updated 2009-03-19]

The arguments property of the Function object looks a lot like an array, but it’s really not. We say it’s array-like since it has a length property and properties whose names are whole numbers.

Similary, DOM properties, such as Element.childNodes, return a NodeList, which is also array-like.

If you’ve ever been frustrated that you can’t use array methods on these array-like collections, then the following function is your new friend:
Continue reading

Javascript inheritance explained 2

Wow. It’s been almost 2 years since I’ve finished a technical blog post! I’ve started plenty, but have just never quite finished any. I figure it’s either because I try to tackle too much in a single post and/or because I am way too picky about the topic. Anyways, here’s a new blog post to prove I didn’t actually fall off the face of the Earth!

In my previous post, I laid out the basic Javascript inheritance mechanism, prototype chaining. In this post, I’ll elaborate on it a bit more by showing how I took this basic concept and created something workable for some very bright, but prototype-phobic programmers: Oracle Life Sciences division’s Java developers! (Java and Javascript couldn’t be more different in almost every regard, especially concerning inheritance.)
Continue reading

Javascript inheritance explained

Most of the Javascript I write is object-oriented. While deciding what I would write about in my first posts, I realized that I would probably have to review Javascript OO techniques first. Any source code I included would be unintelligible to the uninitiated. In this post — and in the subsequent ones — I will review the Javascript inheritance techniques I use and explain why and when I use them.

Continue reading