I know that when source code is compiled, the compiler treats if/elseif/else and switch statements differently making switch statements at least as efficient as a corresponding if/elseis/else and most often more efficient. This is usually done by building a jump-table at compile time that is utilized at runtime. However, for interpreted languages (not compiled) is there any significant efficiency increase when using a switch statement? Surely an interpreter cannot pre-build a jump-table to increase the switch statement's efficiency.

Do interpreters handle switch statements in a way that increases a switch statement's efficiency compared to a corresponding set of if/elseif/else statements?

有帮助吗?

解决方案

My guess is that in interpreted languages, the efficiency benefit in using switch statements is indeed smaller than in compiled languages; the only actual benefit I could think of, is that in a switch statement, the operand (the one which is compared to the different 'cases') will only be evaluated once and will be immediately kept in a register, which won't change and only compare to the different 'cases', whereas if statements could potentially miss that bit and re-evaluate (even if the cost is merely reading from the memory) the operand for every if clause.

In addition, you should also think about readability. In most cases, this performance diference is quite negligible, and you should choose the option which makes your code more readable and understandable.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top