Is ‘switch’ faster than ‘if’?

Is a switch statement actually faster than an if statement? I ran the code below on Visual Studio 2010’s x64 C++ compiler with the /Ox flag: #include <stdlib.h> #include <stdio.h> #include <time.h> #define MAX_COUNT (1 << 29) size_t counter = 0; size_t testSwitch() { clock_t start = clock(); size_t i; for (i = 0; i … Read more

Why does Java switch on contiguous ints appear to run faster with added cases?

I am working on some Java code which needs to be highly optimized as it will run in hot functions that are invoked at many points in my main program logic. Part of this code involves multiplying double variables by 10 raised to arbitrary non-negative int exponents. One fast way (edit: but not the fastest … Read more

Why the switch statement cannot be applied on strings?

Compiling the following code and got the error of type illegal. int main() { // Compilation error – switch expression of type illegal switch(std::string(“raj”)) { case”sda”: } } You cannot use string in either switch or case. Why? Is there any solution that works nicely to support logic similar to switch on strings? 22 Answers … Read more

Switch statement for greater-than/less-than

so I want to use a switch statement like this: switch (scrollLeft) { case (<1000): //do stuff break; case (>1000 && <2000): //do stuff break; } Now I know that either of those statements (<1000) or (>1000 && <2000) won’t work (for different reasons, obviously). What I’m asking is the most efficient way to do … Read more

Case statement with multiple values in each ‘when’ block

The best way I can describe what I’m looking for is to show you the failed code I’ve tried thus far: case car when [‘honda’, ‘acura’].include?(car) # code when ‘toyota’ || ‘lexus’ # code end I’ve got about 4 or 5 different when situations that should be triggered by approximately 50 different possible values of … Read more