var random = Math.floor(Math.random() * 20);
var result = "";
var test = {
"0": "something else",
"1": "something else",
"2": "something else",
"3": "something else",
"4": "something else",
"5": "something else",
"6": "something else",
"7": "something else",
"8": "something else",
"9": "something else",
"10": "something else",
"11": "something else",
"12": "something else",
"13": "something else",
"14": "something else",
"15": "something else",
"16": "something else",
"17": "something else",
"18": "something else",
"19": "something else",
"20": "something else"
};
function getValue(random) {
switch (random) {
case "0":
return "something else";
case "1":
return "something else";
case "2":
return "something else";
case "3":
return "something else";
case "4":
return "something else";
case "5":
return "something else";
case "6":
return "something else";
case "7":
return "something else";
case "8":
return "something else";
case "9":
return "something else";
case "10":
return "something else";
case "11":
return "something else";
case "12":
return "something else";
case "13":
return "something else";
case "14":
return "something else";
case "15":
return "something else";
case "16":
return "something else";
case "17":
return "something else";
case "18":
return "something else";
case "19":
return "something else";
case "20":
return "something else";
default:
return "something else";
}
};
getValue(random);
test[random];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
switch | |
dictionary |
Test name | Executions per second |
---|---|
switch | 37389272.0 Ops/sec |
dictionary | 1391940736.0 Ops/sec |
Let's break down the benchmark test case and explain what's being tested.
Benchmark Definition:
The benchmark is comparing the performance of two approaches:
switch
statementThe script preparation code creates an object test
with 20 properties, each assigned a string value. The getValue
function uses either a switch
statement or dictionary lookup to return the corresponding string value based on a randomly generated number.
Options being compared:
switch
statement to match the input number against a series of cases.Pros and Cons:
Library used:
None explicitly mentioned in the benchmark definition. However, the Math.random()
function is used to generate a random number, which suggests that JavaScript's built-in random number generator is being used.
Special JS feature or syntax:
The use of a dictionary (object) lookup is an example of JavaScript's built-in object-oriented programming features. This syntax is widely supported in modern JavaScript environments and is often preferred for its performance and readability benefits.
Other considerations:
Alternatives:
Other approaches that could be used to compare performance include:
Keep in mind that these alternatives might not provide the same level of performance insight as using an actual JavaScript switch statement or dictionary lookup.