I was curious if anyone knows which of the following executes faster (I know this seems like a weird question but I'm trying to shave as much time and resources as possible off my program.)
int i=0;
i+=1;
or
int i;
i=1;
and I also was curious about which comparison is faster:
//given some integer i
// X is some constant
i < X+1
or
i<=X
For those of you who already posted answers I'm sorry, I edited it so the first section is correct, I meant for if i was initialized to 0. Again sorry for the confusion.
The first operation probably has no meaning because, unless i is static, you've left i uninitialized.
You're misguided and focusing on the wrong things. Guessing isn't going to get you anywhere; bring out a profile, profile your code, and find out with data which parts need to be optimized. Optimizations are design changes, be them different data structures or algorithms.
You heavily underestimate compilers. Nothing you do is going to make a difference with such tiny changes, both will compile to whichever the compiler decides is faster. If you want an integer at one, just do: int i = 1; and live your life. If you want to compare if an integer is less than or equal to X, then just say so: i <= X;. Write clean readable code. On a side note, your two comparisons are not the same when X is at it's maximal value; you'll overflow when you add one.
If you're really serious, again: pull out a profiler. Another thing to do is look at the generated assembly and see which instructions it generates. If you don't know how to do that, chances are you're probably not in a position to need optimization. :/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With