const getSwitch = function (input) {
switch(input) {
case 0:
return 'zero';
case 1:
return 'one';
case 2:
return 'two';
case 3:
return 'three';
case 4:
return 'four';
case 5:
return 'five';
case 6:
return 'six';
case 7:
return 'seven';
case 8:
return 'eight';
case 9:
return 'nine';
case 10:
return 'ten';
}
}
const LUT = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten'
}
const map = new Map([
[0, 'zero'],
[1, 'one'],
[2, 'two'],
[3, 'three'],
[4, 'four'],
[5, 'five'],
[6, 'six'],
[7, 'seven'],
[8, 'eight'],
[9, 'nine'],
[10, 'ten']
]);
const result = getSwitch(Math.floor(Math.random() * 10));
let result;
switch(Math.floor(Math.random() * 10)) {
case 0:
result = 'zero';
break;
case 1:
result = 'one';
break;
case 2:
result = 'two';
break;
case 3:
result = 'three';
break;
case 4:
result = 'four';
break;
case 5:
result = 'five';
break;
case 6:
result = 'six';
break;
case 7:
result = 'seven';
break;
case 8:
result = 'eight';
break;
case 9:
result = 'nine';
break;
case 10:
result = 'ten';
break;
}
const result = LUT[Math.floor(Math.random() * 10)];
const result = map.get(Math.floor(Math.random() * 10));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
switch function | |
switch inline | |
object | |
Map |
Test name | Executions per second |
---|---|
switch function | 20525988.0 Ops/sec |
switch inline | 32947854.0 Ops/sec |
object | 164263936.0 Ops/sec |
Map | 696350016.0 Ops/sec |
The benchmark defined by MeasureThat.net compares the performance of four different approaches to returning a string representation of numbers from 0 to 10 using JavaScript. The options being tested are:
switch
statement.switch
statement without a surrounding function.Map
object for the same lookup purpose.switch
statement to return the appropriate string.new Map()
to create a map of number-string pairs and retrieves the string using the .get()
method.The benchmark results showcase the performance of each approach measured in executions per second:
Overall, the benchmark provides valuable insights into the performance differences among these strategies for mapping numeric values to strings in JavaScript, enabling developers to make informed choices based on context and requirements.