Lazy dictionary

Benchmark created on


Description

Simple test to measure the performance difference when a multitude of possible results need to be computed in such a way that using a dictionary to select them would be the best design, but computing the results before storing them in the dictionary would lead to a lot of unnecessary computation.

Preparation HTML

<script>
function longCalculation(result) {
  window.setTimeout(function() { return result; }, 100);
}
var choices = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var choice;

function simpleConditionalCalculation(key) {
  var simpleDict = {};
  for (i=0; i<choices.length; i++) {
    simpleDict[choices[i]] = longCalculation(null);
  };
  return simpleDict[key];
}

function lazyConditionalCalculation(key) {
  var lazyDict = {};
  for (i=0; i<choices.length; i++) {
    lazyDict[choices[i]] = function() { return longCalculation(null); };
  };
  return lazyDict[key]();
}

</script>

Setup

choice = choices[Math.floor(Math.random() * choices.length)];

Test runner

Ready to run.

Testing in
TestOps/sec
Simple conditional calculation
simpleConditionalCalculation(choice);
ready
Lazy conditional calculation
lazyConditionalCalculation(choice);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.