Pick random property from object

JavaScript performance comparison

Test case created

Info

Select a property from a javascript object at random.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var obj = {
      test: 'test',
      test1: 'test1',
      test2: 'test2',
      test3: 'test3',
      test4: 'test4',
      test5: 'test5',
      test6: 'test6',
      test7: 'test7',
      test8: 'test8',
      test9: 'test9',
      test10: 'test10',
    };
   
    function pickRand1(obj) {
        var result;
        var count = 0;
        for (var prop in obj)
            if (Math.random() < 1/++count)
               result = prop;
        return result;
    }
   
    function pickRand2(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)]];
    }
};
</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
Random 1
pickRand1(obj);
pending…
Random 2
pickRand2(obj);
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