• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

++i vs i++

 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code:



Would ++i have been faster, execution-wise? I read somewhere way back (in Programming Gems I believe) that even in such cases, extra work must be done to make sure i can be incremented 1 after it's value is used in the expression (for i++ that is). It was based on c++, but I am wondering if i++ and ++i makes any difference here for java.

Thanks in advance.
 
Guido Sautter
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try out printing the value of i within the loop with both variants, ad see what you get ... Hint:
- i++ is a post-increment
- ++i is a pre-increment
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Leave speed of execution as your last priority.
There is very little difference between ++i and i++ compared to the remainder of the loop, and I don't think there will be a difference in the body of the loops.

It is customary to use i++ when it is on its own. Since a for loop is a standardised construct, you will make maintenance much more difficult if you use uncoventional formats.
 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But there is a difference?

I mean,




don't have much difference in maintainability. With the same results,
the difference on performance would be my motivation to go with it.

I was just wondering about this, with the quality matrix aside of course. And I understand that design patterns and bottleneck analysis have a much greater impact on improving performance, but for the sake of adventure I tell you!

So...does it actually have a difference? Why is i++ the standard then I wonder.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're really that worried about it why don't you try disassembling it and see what instructions are actually used.
 
Ronald Schild
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess it comes to that. Thanks for the tip though
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic