Random object key

JavaScript performance comparison

Test case created by Harpyon

Preparation code

<script>
  var MrArray = new Array(5);
  MrArray['one'] = 'oneValue';
  MrArray['two'] = 'twoValue';
  MrArray['three'] = 'threeValue';
  MrArray['four'] = 'fourValue';
  MrArray['five'] = 'fiveValue';
 
  function randomValue1(obj) {
    var ret;
    var c = 0;
    for (var key in obj)
    if (Math.random() < 1 / ++c) ret = key;
    return obj[ret];
  }
 
  function randomValue2(obj) {
    var temp_key, keys = [];
    for (temp_key in obj) {
      if (obj.hasOwnProperty(temp_key)) {
        keys.push(temp_key);
      }
    }
    return obj[keys[Math.floor(Math.random() * keys.length)]];
  }
 
  var foo;
</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
First method
foo = randomValue1(MrArray);
pending…
Second method
foo = randomValue2(MrArray);
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