title: JavaScript: Fast random indexing of object keys
body: <p>I am attempting to randomly select a random property from an object that I use as a dictionary for fast indexing.</p>
  
  <p>Consider the following code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//Create test dictionary
  var dict = {};
  for(var i = 0; i &lt; 10000; i++) {
    var num = Math.random() * 1000000 &lt;&lt; 0;
    dict[num] = { Id: num };
  }
  
  //Fuzz
  const NUM_RUNS = 1000;
  var start = new Date();
  for(var i = 0; i &lt; NUM_RUNS; i++)
    getRandom(dict);
  var end = new Date();
  
  var runTime = (end.getTime() - start.getTime()) / 1000;
  var timePerCall = (runTime / NUM_RUNS) * Math.pow(10,9);
  console.log('Total Calls: ' + NUM_RUNS);
  console.log('Total Runtime: ' + runTime + ' seconds');
  console.log('Time Per Call: ' + timePerCall + ' nanoseconds');
  
  
  
  function getRandom(dict) {
    var keys = Object.keys(dict);
    var index = keys[Math.random() * keys.length &lt;&lt; 0];
    return dict[index];
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>As you can see, using <code>Object.keys()</code> is <strong>very</strong> expensive, especially as the dictionary grows.</p>
  
  <p>I am looking for an optimal way to achieve random selection of an element in the dictionary. Of course, having 10000+ elements in the dictionary is an extreme edge case, but I would like to be able to handle it nonetheless.</p>