Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Back when I started programming in college, a friend encouraged me to use the prefix incrementation operator ++i instead of the postfix i++, citing that there was a slight chance of better performance with no real chance of a downside. I realize this is true in C++, and it's become a general habit that I continue to do.

I'm led to believe that it makes little to no difference when used in a loop in C#, regardless of data type. Apparently the ++ operator can't be overridden. Nevertheless, I like the appearance more, and don't see a direct downside to it.

It did astonish a coworker just a moment ago though, he made the (fairly logical) assumption that my loop would terminate early as a result. He's a self-taught programmer, and apparently never came across the C++ convention. That made me question whether or not the equivalent behavior of pre- and post-fix increment and decrement operators in loops is well known enough.

Is it acceptable for me to continue using ++i in looping constructs because of style preference, even though it has no real performance benefit? Or is it likely to cause confusion amongst other programmers?


  • Note: This is assuming the ++i convention is used consistently throughout all code.
share|improve this question
2  
"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%." - Donald Knuth –  Jesse C. Slicer Sep 11 '12 at 20:47
4  
@JesseC.Slicer This quote was not needed. The question is about coding style. The OP is aware that there is no performance gain with the prefix operator. –  marco-fiset Sep 11 '12 at 20:54
2  
@marco-fiset the OP could pass the quote along to his coworker, who appears to need it. –  Jesse C. Slicer Sep 11 '12 at 21:31
    
@JesseC.Slicer I assume you mean the person who told me about it in the first place. I'd argue that this doesn't fall under the same category as a lot of premature optimization. There are never any negative effects from doing it, it doesn't take more effort to do, and it's not convoluted (well, I'm clearly biased on that point...). In some languages (C++) it can either have beneficial effects, or none what so ever. It's kind of a "why not" sort of thing. –  KChaloux Sep 11 '12 at 21:40
    
@KChaloux Yes, I mean the person who told you. My take is don't go changing because you heard it's harmless and could have a performance bump. 1) the likelihood of the bump is close to nil for the common case, 2) the overall performance increase is negligible compared to the time refactoring and 3) look elsewhere if performance is the key element and 4) beware introducing subtle unintended logic changes. All that being said, if you're creating a new convention, by all means, choose ++i if you feel it's right for you and your team. –  Jesse C. Slicer Sep 11 '12 at 22:26

6 Answers 6

up vote 10 down vote accepted

I think you should stick with the conventions that your co-workers are used to. The principle of least surprise. You don't want to sit and figure out why a simple operation is written in an uncommon manner for no reason, so why should the next guy who is reading your code?

share|improve this answer
    
Does it make a difference if his last day is this Thursday, and he left me the only person in the company that knows how to write C# at all? Because that's the situation :p –  KChaloux Sep 11 '12 at 20:02
1  
You should follow good clean coding principles. Today you might be the only guy, tomorrow they might get another developer or someone will be looking at your code when you leave. You want to develop good coding habits early on. –  Nik Sep 11 '12 at 20:09
    
Alright, that's fair enough advice. It's just going to take a few weeks of overwriting my muscle memory to not go for the ++ first :p –  KChaloux Sep 11 '12 at 20:29
1  
@Nik: tomorrow there will be another senior dev who prefers ++i instead of i++ in loops. Honestly, I would be tolerant about those two options and expect everyone in my team having no diffculties to read both variants. –  Doc Brown Sep 11 '12 at 20:42

Unoptimized, i++ makes a copy, so j = i++ translates to:

iTemp = i;
i = i + 1;
j = iTemp;

Whereas j = ++i translates to:

i = i + 1;
j = i;

That extra copy into a temp variable is what causes the theoretical performance hit with the post-increment. However, since the new value of i doesn't depend on j, it can be optimized to:

j = i;
i = i + 1;

Which, barring any pipeline oddities, has exactly the same runtime as the pre-increment version. It turns out there are very few real world circumstances where a similar compiler optimization is not possible, so there is practically zero reason to choose pre-increment for optimization reasons. Standalone increments, such as in a for loop, are even easier to optimize down to the same instruction.

In other words, follow the coding convention unless it's syntactically significant. But it doesn't hurt to educate your colleagues either if the only reason they don't use it is based on an erroneous understanding of how for loops work.

share|improve this answer
    
+1 Thanks for the explanation. But I did not see this translation in any documentation. Can u share any link ? –  Pankaj Garg Jul 9 '13 at 13:49

++i and i++ are different operations.

Check this Link out it gives a better example than what I had. but I was on the Right Track.

int i = 1;

Console.WriteLine(++i); // <-- will output 2



i = 1; // <-- reset i

Console.WriteLine(i++); // <-- will output 1
share|improve this answer
    
Different operators, but your conclusion is not accurate, if your //some Code is replaced with Console.WriteLine(i); it will output the numbers 0 to 19 in both. –  CaffGeek Sep 11 '12 at 20:21
    
fyi, I didn't downvote you –  CaffGeek Sep 11 '12 at 20:25
1  
in the case of for loops pre/post increment doesn't really matter, because the increment is its own distinct step. the difference matters when the increment is combined with other operations –  Ryathal Sep 11 '12 at 20:33

Good practice is to use the coding convention that your team members/colleges are agreed on. It does not really matter how you decided to do that as far as it works and inconstantly implemented. Keeping code as simple and as clean (KISS principle) should be the main goal.

It is far more important to have consistent style of coding in big projects to ease the maintenance at later stages.

Here you are a MS guidelines link - C# Coding Conventions (C# Programming Guide)

share|improve this answer

I would say that depends upon exactly what you mean by "style preference". If you mean that you want to use "++i" everywhere including loops like for(i=0; i<x; ++i), then that's fine. If on the other hand you want to specifically use it in loops while elsewhere using i++ or i+=1 (or viceversa) then that's a terrible idea, you should be consistent through-out the program.

As long as you are consistent and aren't using it in a comparision expression or multiple times in a method call, this should not be a suprise to anyone. In particular the for loop is

  1. Assignment
  2. Comparison
  3. Body, if, true, and Finally
  4. Increment

As long as you aren't doing your increment in either 1, 2 or 3, there should be no surpise.

On the other hand, if you sometime use post increment and sometimes pre increment, or do it in a non standard manner f(i++, ++i);, then you're going to give someone pause, and you're likely to make a mistake yourself or lead someone else into making a mistake.

Note that if you do choose ++i, I would recommend that you Never do this if(++i<x)...

share|improve this answer

It's true that i++ and ++i are different operations. They have the same side effect (modifying the stored value of i), but they yield different values, and as Karl Bielefeldt's answer points out an unoptimized implementation of i++ may have to store the previous value of i in a temporary.

But if you're using them in a context where the result is not used, there should be no difference at all.

For example, in a C-style for loop, the third expression in the loop header is evaluated only for its side effects; any value it yields is quietly discarded. These two loops:

for (i = 0; i < COUNT; i ++) {
    // ...
}

for (i = 0; i < COUNT; ++ i) {
    // ...
}

have identical semantics, and if your compiler doesn't generate identical, or at least equivalent, code for both you should probably find a better compiler.

So in this context, the choice between i ++ and ++ i should be purely one of style. If you have a coding standard, follow it. If you don't, just be consistent.

If you're using either i ++ or ++ i in a context where the result is used, then performance isn't going to be a factor; use whichever one gives you the answer you need. Or consider whether your code might be cleaner if you rearrange it so you're not using the result of i ++ or ++ i.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.