Random object key

JavaScript performance comparison

Test case created by Harpyon

Preparation code

  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)) {
    return obj[keys[Math.floor(Math.random() * keys.length)]];
  var foo;

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);
Second method
foo = randomValue2(MrArray);

Compare results of other browsers


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:


Comment form temporarily disabled.

Add a comment