Reputation: 147
I have a code to generate math problems with random numbers. I am using switch statement to choose which task should be generated.
function genTask(taskid) {
switch (taskid) {
case 1:
// generate some numbers
return numbers;
break;
case 2:
// generate some numbers
return numbers;
break;
// ...
}
}
I think there may be some performance issues when I add 150+ cases. Does this code go trough every case? Wouldnt it be faster if there are separate functions for every task?
function task1() {
// generate some numbers
return numbers;
}
function task2() {
// ...
}
function genTask(taskid) {
switch (taskid) {
case 1:
return task1();
break;
case 2:
return task2();
break;
// ...
}
}
Is there a faster way to do this?
Upvotes: 1
Views: 782
Reputation: 1298
In general, I think the performance of "array" is better than "if/else" or "switch". See the reference below. In your specific case, if you comparing if/else to switch, then switch is better.
Using functions will not affect the performance ( I think ), but it is better and preferable as the code will be cleaner and readable.
Reference : https://www.oreilly.com/library/view/high-performance-javascript/9781449382308/ch04.html
Upvotes: 2
Reputation: 2111
First of all, you need to know where you need to use if/else
or switch/case
.
When you need to check 2 to 3 conditions then you can use if/elseif/else
When you need to check 5 or above then definitely use switch/case
And based on speed switch/case
is faster then if/else
Let's get back to the original point, In your case, you have 2 choices
Write all code in one switch case.
Make functions in chunk and call-in switch case.
I suggest you go with the second choice because switch case also a faster way of execution compared to other conditional checks, But when you make different functions then you can easily modify it and debug it which more help in development, and performance not compromised in that case.
Upvotes: 1
Reputation: 465
One more approach is you can use a object lookup
function task1() {
// generate some numbers
return numbers;
}
function task2() {
// some task
}
const taskMap = { 1: task1, 2: task2 };
function genTask(taskid, defaultVal) {
return (taskMap[taskid] && taskMap[taskid]()) || defaultVal;
}
This will be simple object lookup, though in terms of performance it might be slower than switch case but it increases resuability and readability of the code.
Upvotes: 1