What is the performance of a lookup table of functions? The same assignment statement is executed on the value string (which is set to "dog").
var value =
"dog";
var y = 0;
var dict = {
"fish": function() {
y = 0;
},
"cat": function() {
y = 10;
},
"dog": function() {
y = 20;
}
}
var x1 = performance.now();
// Version 1: call method in dictionary.
for (var i = 0; i < 100000000; i++) {
dict[value]();
}
var x2 = performance.now();
// Version 2: use switch to run code based on a string value.
for (var i = 0; i < 100000000; i++) {
switch (value) {
case
"fish":
y = 0;
break;
case
"cat":
y = 10;
break;
case
"dog":
y = 20;
break;
}
}
var x3 = performance.now();
// Results.
console.log(
"TIME 1: " + (x2 - x1));
console.log(
"TIME 2: " + (x3 - x2));
TIME 1: 186.135
TIME 2: 185.485