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.
In both runs, fixKeysClosure was the slowest, by a lot. Concatenation and join() weren’t that different.