What's the most efficient way to turn an object's keys to its lowercase version

JavaScript performance comparison

Revision 7 of this test case created by Jason Orendorff

Info

http://stackoverflow.com/questions/12539574/whats-the-best-way-most-efficient-to-turn-all-the-keys-of-an-object-to-lower

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    // make an object with 6^4=1296 keys
    this._objects = [];
    for (var a = 0; a < this.count; a++) {
      var obj = {};
      var s = ['Ni', 'Icki', 'Ptang', 'Zoo', 'Weep', 'Ninnybon'];
      for (var i = 0; i < s.length; i++)
        for (var j = 0; j < s.length; j++)
          for (var k = 0; k < s.length; k++)
            for (var l = 0; l < s.length; l++)
              obj[s[i] + s[j] + s[k] + s[l]] = 0;
      this._objects[a] = obj;
    }
    this._index = 0;
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
joaojeronimo's function
  var obj = this._objects[this._index++];
  var keys = Object.keys(obj);
  var n = keys.length;
  while (n--) {
    var key = keys[n];
    if (key !== key.toLowerCase()) {
            obj[key.toLowerCase()] = obj[key]
            delete obj[key]
        }
  }

 
pending…
Don't check if the key is already in lower case
// Might be cheaper to just change it, but I doubt it
  var obj = this._objects[this._index++];
  var keys = Object.keys(obj);
  var n = keys.length;
  while (n--) {
    var key = keys[n];
    obj[key.toLowerCase()] = obj[key]
    delete obj[key]
  }
pending…
Create a second object instead of modifying the first
var obj = this._objects[this._index++];
var keys = Object.keys(obj);
var obj2 = {};
var n = keys.length;
while (n--) {
    var key = keys[n];
    obj2[key.toLowerCase()] = obj[key];
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment