File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes ++i vs i++ Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "++i vs i++" Watch "++i vs i++" New topic
Author

++i vs i++

Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
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.


Java hobbyist.
Guido Sautter
Ranch Hand

Joined: Dec 22, 2004
Posts: 142
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

Joined: Oct 13, 2005
Posts: 40052
    
  28
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

Joined: Jun 09, 2008
Posts: 117
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

Joined: Aug 05, 2005
Posts: 3742
    
  16
If you're really that worried about it why don't you try disassembling it and see what instructions are actually used.


Joanne
Ronald Schild
Ranch Hand

Joined: Jun 09, 2008
Posts: 117
I guess it comes to that. Thanks for the tip though
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ++i vs i++