Benchmarking String Function to camelCase

I needed a function to turn snake_case to camelCase. The reason why? Angular and Javascript are better with camelCase, and Python and Django prefer snake_case. I tried working with both in the Django side, and it wasn’t pretty. Even worse, I lost track of when I switched from one to the other, if I switched at all. So, I’m going to try renaming the keys as they are handed off from Django Rest Framework to the Javascript.

There were a bunch out there that used String.replace with a callback. It’s terse, but looked slow to me. So I decided to write a few different versions and test them out.

function camelCaseClosure( word ) {
    return word.replace(/_([a-z])/g, function(g) { return g[1].toUpperCase(); }); 
}

function camelCaseString( word ) {
    var newword = ""; 
    var j=0;
    for(var i=0,l=word.length; i<l; i++) {
        if (word[i]=='_') {
            newword += word[i+1].toUpperCase();
            i++;
        } else {
            newword += word[i];
        }
        j++;
    }
    return newword;
}

function camelCaseJoin( word ) {
    // var newword = new Array( word.length ); // much slower on chrome
    var newword = [];
    var j=0;
    for(var i=0,l=word.length; i<l; i++) {
        if (word[i]=='_') {
            newword[j] = word[i+1].toUpperCase();
            i++;
        } else {
            newword[j] = word[i];
        }
        j++;
    }
    return newword.join();
}

// a testing function
function fixKeysClosure( hash ) {
    var newhash = {};
    var keys = Object.keys(hash);
    for(var i=0, l=keys.length; i < l; i++) {
        k = keys[i];
        newhash[ camelCaseClosure(k) ] = hash[ k ];
    };
    return newhash;
}

I didn’t include all the testing code, but it all looks like fixKeysClosure. It changes the keys in a hash to camel case.

Firefox v33 results, 500,000 iterations, in ms:
fixKeysClosure 3880
fixKeysString 2209
fixKeysJoin 2829

Chromium v38 results:
fixKeysClosure 2087
fixKeysString 753
fixKeysJoin 791

So the string version, using the usual concatenation, is fastest. This includes a superfluous variable, j, which I didn’t need.

fixKeysJoin was a lot slower on Chrome if you pre-allocated an array of the correct size.

A function to convert the keys of an array to camel case is attached.

Attachment Size
test.html 1.25 KB