<!--your preparation HTML code goes here-->
const f1 = () => {}
const f2 = () => {}
const f3 = () => {}
const f4 = () => {}
const f5 = () => {}
function getFnIf(level) {
if (level === "info") return f1;
else if (level === "warn") return f2;
else if (level === "error") return f3;
else if (level === "fatal") return f4;
else return f5;
}
function getFnSwitch(level) {
switch (level) {
case "warn":
return f1;
case "info":
return f2;
case "error":
return f3;
case "fatal":
return f4;
default:
return f5;
}
}
const lookup = {
'info': f1,
'warn': f2,
'error': f3,
'fatal': f4
}
function getFnLookupString(level) {
return lookup[level] || f5
}
const lookupN = {
'1': f1,
'2': f2,
'3': f3,
'4': f4
}
function getFnLookupN(level) {
return lookupN[level] || f5
}
const arr = [f1,f2,f3,f4,f5]
function getFnLookupA(level) {
return arr[level] || f5
}
getFnIf('info')
getFnIf('warn')
getFnIf('error')
getFnIf('fatal')
getFnIf()
getFnSwitch('info')
getFnSwitch('warn')
getFnSwitch('error')
getFnSwitch('fatal')
getFnSwitch()
getFnLookupString('info')
getFnLookupString('warn')
getFnLookupString('error')
getFnLookupString('fatal')
getFnLookupString()
getFnLookupN('1')
getFnLookupN('2')
getFnLookupN('3')
getFnLookupN('4')
getFnLookupN()
getFnLookupA(0)
getFnLookupA(1)
getFnLookupA(2)
getFnLookupA(3)
getFnLookupA()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
if | |
switch | |
lookup with strings | |
lookup with number | |
lookup in array |
Test name | Executions per second |
---|---|
if | 146164656.0 Ops/sec |
switch | 145137392.0 Ops/sec |
lookup with strings | 71823064.0 Ops/sec |
lookup with number | 41335268.0 Ops/sec |
lookup in array | 43572224.0 Ops/sec |
This benchmark explores the performance differences between various methods of selecting functions in JavaScript based on a specific input "level." The primary methods being compared are:
getFnIf
)getFnSwitch
)getFnLookupString
)getFnLookupN
)getFnLookupA
)If-Else Statements (getFnIf):
Switch Statements (getFnSwitch):
Lookup Object with Strings (getFnLookupString):
Lookup Object with Numbers (getFnLookupN):
Lookup in Array (getFnLookupA):
Based on the results from the benchmark, the performance measured in executions per second showcased the following order of efficiency:
if
and switch
) and lookup approaches.Other alternatives include:
Map
object in JavaScript is better suited for dynamic key-value pairs and can provide better performance for size and key complexity.This benchmark serves to inform developers about these decisions, providing insight into when it may be suitable to opt for one approach over the other based on performance needs and code maintainability.