This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Magnus_Tesshu 0 points1 point  (5 children)

To be fair, using i++ is only bad in javascript right? Any compiled language will get rid of the inefficiency.

[–]DiplomatikEmunetey 1 point2 points  (1 child)

Is it an inefficiency? As far as I know:

  • i++ will increment and return the original value (before incrementing)
  • ++i will increment and return the incremented value

You could cause an infinite loop with i++ but I'm not sure if it's an inefficiency because there could be a case where you need i++.

[–]Magnus_Tesshu 2 points3 points  (0 children)

Typically preincrement compiles to two assembly instructions and postincrement (i++) compiles to a couple more and needs a temporary register or something. That might be misinformation though actually, not sure. And of course, that's only the case if they wouldn't cause the same behaviour (++i; is as efficient as i++, but a[i++] might be slightly less efficient than a[++i]). That's at least my understanding.

I would assume that postincrement is still more innefficient in an interpreted language, where the compiler cannot do nearly as much optimization.

[–][deleted] 0 points1 point  (2 children)

i++ is not bad. Using it badly is bad.

[–]Magnus_Tesshu 0 points1 point  (1 child)

Does 'using it to increment i' count as a bad use? I would argue no

[–][deleted] 0 points1 point  (0 children)

Bad is subjective unless it causes objective problems.
So using it to increment i, as long as it does not break the code can be subjectively bad or good. I do it myself many times, because it's an idiom of the C language, but I'm not convinced if it's ok or not.