Is Switch Faster Than a Lookup Table in JavaScript? A 50,000-Iteration Test
After reading 'High-Performance JavaScript', I tested the speed of a switch statement versus a lookup table over 50,000 iterations, finding the switch slightly faster contrary to the book’s claim, and reflecting on the practical benefits of lookup tables such as clearer code and easier maintenance.
In the book “High‑Performance JavaScript” a “lookup table” is recommended as faster than if‑else or switch when many discrete values need to be tested. To verify this claim I wrote two functions – one using a switch statement and another using a lookup table – and measured their execution time over 50 000 iterations.
Switch version (illustrated in the first screenshot):
Lookup‑table version (second screenshot):
The test code used was:
var index = 0;
console.time('test');
for (var i = 50000; i >= 0; i--) {
index = index == 10 ? 0 : index;
// simulate a lookup or switch call
// search(index++);
}
console.timeEnd('test');Running the test five times produced the following results (in milliseconds):
Switch: 1.25, 0.91, 1.22, 1.31, 0.89
Lookup table: 1.86, 1.43, 3.13, 1.08, 1.05
Contrary to the book’s assertion, the switch implementation was slightly faster on average. The difference, however, is marginal and unlikely to affect overall system performance.
Beyond raw speed, the lookup‑table approach has two clear advantages:
Code clarity : the logic is more straightforward than a long chain of if‑else or switch cases.
Maintainability : adding or removing conditions only requires updating the table, not restructuring control flow.
From this experiment I learned two lessons:
Never rely solely on book recommendations; empirical testing is essential.
Even familiar patterns deserve reconsideration when alternative solutions may offer better readability or maintainability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
