Forums Register Login

For or If-Else?

+Pie Number of slices to send: Send
Hi,
Anyone know what is faster: A for loop running 200 times or 200 if-else statements? Thanks!
+Pie Number of slices to send: Send
I'm not 100% sure how java handles these two instructions at the machine level, but in all 3GLs I've worked with If/Else is faster than a For-loop or something similar.
You should probably still use the For-loop however, since the speedloss is very marginal and readability and maintainability are much better.
+Pie Number of slices to send: Send
Do you mean
if
else
if
else
if
else
if
else
if
else
if
else
if
else
if
else
if
else
if
else
if
else
.
.
.
???

What a mess!!
[ February 09, 2004: Message edited by: Marilyn de Queiroz ]
+Pie Number of slices to send: Send
 

Originally posted by P. Sagdeo:
Hi,
Anyone know what is faster: A for loop running 200 times or 200 if-else statements? Thanks!


Care to explain why you would want to write 200 if-else statments? What will you do if you realize that you need an additional 100?
+Pie Number of slices to send: Send
Moving this to the Performance forum...
+Pie Number of slices to send: Send
 

Originally posted by Maarten Vergouwen:
I'm not 100% sure how java handles these two instructions at the machine level, but in all 3GLs I've worked with If/Else is faster than a For-loop or something similar.


Yeah, but with Hotspot the for loop could actually be faster, as the more often some code gets executed, the more it will get optimized...
+Pie Number of slices to send: Send
This really is an apples vs. oranges comparison, I think. Loops and if/else statements do completely different things, and the speed of each one is very much dependent on what you do inside each of these constructs, which we have no information about. Can you show an example of what the code you're comparing would look like? What are you trying to do?
If you're thinking about having 200 if / else if statements, there's often a better way, say by using a switch statement, or doing some sort of lookup in an array, HashMap, or TreeMap. If you show a bit more of what you're doing, we can give better info on how this might work.
+Pie Number of slices to send: Send
if-else is not repeatitive. It will not receive the same optimizations in any language that a for loop will.
I've got no option but to sell you all for scientific experiments. Or a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 953 times.
Similar Threads
garbage collection problem
Tricky task! Help needed...
If-Else vs For
SCWCD voucher for sale
add up differnt values in loop
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 06:15:29.