Log in

View Full Version : Resolved Is switch or if and else more memory efficient



twQ
01-04-2010, 01:26 AM
The application would be you have a number between 1 and 3 and depending on how many numbers there are that changes what the output is. Would it be more efficient to use switch or if else if and else?

Tim

Nile
01-04-2010, 01:32 AM
Use switch, if anything I think it should take less time to load.

twQ
01-04-2010, 01:34 AM
Thats what I've been using it was more curiosity. Thanks Nile.

Tim

Nile
01-04-2010, 01:40 AM
Glad to help! When I said I think it takes less time, please note that I, as a programmer, don't care if the page takes 10 more mili seconds then it should. :D

djr33
01-04-2010, 02:35 AM
Realistically I doubt that it will matter. You can test it by doing something like 1000 iterations of a loop with it, then compare the results.
However, this is going to be more of an issue for much longer sets. The use of switch statements is when you have too many items to easily setup if/else statements, where you'd end up inside the 50th else-- at that point it's a much better idea for your sanity if nothing else to use the more "flat" switch statements. They may run faster, but I really have no idea what is behind them-- for all I know it may just be a shortcut the writing the equivalent if/else statements, though probably not since it is a basic element of the language.

twQ
01-04-2010, 05:04 PM
Yeah I see what you mean. I use switches because I find them easier to read in the code sometimes. Other times if/else makes more sense.

BTW Nile every time I read your name I think of this death metal band named Nile hahaha.

Thanks for the answers, I doubted it would make much to any difference but in the future this stuff could be a big deal (probably not but maybe).:D