++i is faster than i++ in Java?

J

jrefactors

I want to know in Java, is prefix operator faster than postfix
operator?

for example, ++i is faster than i++. I know in C++, this is the case,
but not sure if Java is the same.


please advise. thanks!!
 
A

Andrew Thompson

I want to know in Java, is prefix operator faster than postfix
operator?

What did your bechmark suggest? Post the code and I'll
give you some figures for my machine as well.
 
T

Thomas Hawtin

I want to know in Java, is prefix operator faster than postfix
operator?

for example, ++i is faster than i++. I know in C++, this is the case,
but not sure if Java is the same.

The issue in C++ occurs when the ++ postfix operator is overloaded. The
overload function needs to return a copy of the original object. The
prefix operator can get away with just returning a reference.

Java does not (yet) allow operator overloading, so the issue does not arise.

Tom Hawtin
 
R

Roedy Green

I want to know in Java, is prefix operator faster than postfix
operator?

for example, ++i is faster than i++. I know in C++, this is the case,
but not sure if Java is the same.

Java is a language. It does not have a speed. All you can talk about
is the code generated by some particular compiler/runtime
implementation on some particular computer.

In theory ++i should be slightly slower than i++ since i can be used
right away with i++, then incremented at leisure any time there is a
hole in the instruction pipeline to do it before i is again next
needed. With ++i, all has to wait while i is first incremented.

However, a clever optimiser could likely do either equally quickly by
fitting in the increment ahead of time in some unused pipeline time.

In a machine like the AMDs, you don't even see this level of
optimisation. It is all done on the fly by hardware.

It is not the sort of thing to fret over. Most idiomatic code uses
i++ for historic reasons. Avoiding confusing others by using i++ when
you have a choice.
 
T

Thomas Hawtin

Roedy said:
It is not the sort of thing to fret over. Most idiomatic code uses
i++ for historic reasons. Avoiding confusing others by using i++ when
you have a choice.

Or ++i because it is more consistent with C++ code and is a simpler
operator. Just one or the other.

Tom Hawtin
 
T

Tris Orendorff

(e-mail address removed) wrote in
I want to know in Java, is prefix operator faster than postfix
operator?

for example, ++i is faster than i++. I know in C++, this is the case,
but not sure if Java is the same.


please advise. thanks!!

I advise you to use the ++C compiler because I KNOW it is faster than the
C++ compiler.



--

Sincerely,

Tris Orendorff
[Two antennae meet on a roof, fall in love and get married. The ceremony
wasn't much, but the reception was excellent.]
 
K

Kari Ikonen

I want to know in Java, is prefix operator faster than postfix
operator?

for example, ++i is faster than i++. I know in C++, this is the case,
but not sure if Java is the same.

Neither one is faster in java, since code generated for
"i++", "++i", "i += 1" and "i = i + 1" is exactly same.
 
B

Benji

In said:
I want to know in Java, is prefix operator faster than postfix
operator?
for example, ++i is faster than i++. I know in C++, this is the case,
but not sure if Java is the same.

rule 0: the compiler is smarter than you are.

chances are any code that you write with either ++i or i++ is going to
get compiled to the exact same code. if javac (or the java vm, depending
on where the optimization is made) detects that it doesn't to depend on
what the result is, it's probably going to generate the same native code.

Even if there were a slight performance increase, it would be SO
incredibly small compared to all of the other overheads in your program
that it is completely not worth worrying about. I guarentee you that a
there is no program you could write that would result in more than a
..01% overhead due to doing the increment the "wrong way", if there
was a wrong way.

Your real adversary is excessive memory usage on most systems. As far as
how you code your algorithms, what is more important is readability and
maintainability (within reason - obviously if you affect the big-O of
the algorithm, or if it is a very tightly-run loop)

If you have a program where something like that would matter, you
probably shouldn't be using java in the first place, since being
garbage-collected is a pretty big overhead.

But, in summation, I'd be willing to bed that they'd both get compiled
down to the same code. (in java or in c) Especially with variables with
function-scope, the java compiler has plenty of opportunity to optimize
away any "inefficiencies" you might have. You'd be surprised at how
smart they are on the method level.

A common mistake that people make in c is thinking that using inlined
assembly will make their program faster, when in reality, they're just
sticking a block of unoptimizable code in the middle of their function,
and crippling the compiler's ability to do its job as well as it could.
 
B

Benji

In said:
I want to know in Java, is prefix operator faster than postfix
operator?
for example, ++i is faster than i++. I know in C++, this is the case,
but not sure if Java is the same.

rule 0: the compiler is smarter than you are.

chances are any code that you write with either ++i or i++ is going to
get compiled to the exact same code. if javac (or the java vm, depending
on where the optimization is made) detects that it doesn't to depend on
what the result is, it's probably going to generate the same native code.

Even if there were a slight performance increase, it would be SO
incredibly small compared to all of the other overheads in your program
that it is completely not worth worrying about. I guarentee you that a
there is no program you could write that would result in more than a
..01% overhead due to doing the increment the "wrong way", if there
was a wrong way.

Your real adversary is excessive memory usage on most systems. As far as
how you code your algorithms, what is more important is readability and
maintainability (within reason - obviously if you affect the big-O of
the algorithm, or if it is a very tightly-run loop)

If you have a program where something like that would matter, you
probably shouldn't be using java in the first place, since being
garbage-collected is a pretty big overhead.

--edit--
actually, if you have a program that is a series of tight loops,
java could actually be faster than c or c++, since it does the
actual compilation to native code on the fly. But anyway, the
point is, you don't really need to worry about it.
--end edit--

But, in summation, I'd be willing to bed that they'd both get compiled
down to the same code. (in java or in c) Especially with variables with
function-scope, the java compiler has plenty of opportunity to optimize
away any "inefficiencies" you might have. You'd be surprised at how
smart they are on the method level.

A common mistake that people make in c is thinking that using inlined
assembly will make their program faster, when in reality, they're just
sticking a block of unoptimizable code in the middle of their function,
and crippling the compiler's ability to do its job as well as it could.
 
L

Luc The Perverse

Thomas Hawtin said:
Or ++i because it is more consistent with C++ code and is a simpler
operator. Just one or the other.

Tom Hawtin

C++ uses either. But I have seen i++ (by itself) much more than i++.

I don't know about . . . simpler?

When you are using i in a statement, use the one that is appropriate, they
don't return the same value.
 
T

Thomas Hawtin

Luc said:
C++ uses either. But I have seen i++ (by itself) much more than i++.

You can use either in C++, but any half-decent body of code will prefer
pre-increment. The other choices are to be inconsistent or create
unnecessary temporaries.
I don't know about . . . simpler?

Simpler in the sense that as it returns there is only one value
involved. ++i quite simply returns the value of i. i++ returns a copy of
the value that i used to have before the operation was performed, so you
have to contend with two values at once.

Tom Hawtin
 
R

Roedy Green

Simpler in the sense that as it returns there is only one value
involved. ++i quite simply returns the value of i. i++ returns a copy of
the value that i used to have before the operation was performed, so you
have to contend with two values at once.

Here is an SSCCE to investigate the byte code generated by i++ and
++i. Hotspot optimised code is quite another matter, investigating
pipeline lookahead yet another.

public class PreIncrement

{
/**
* investigate byte code for/pre post incremement
* disassemble with javap.exe -c PreIncrement
* @param args not used
*/
public static void main ( String[] args )
{
int post=0;
int pre=0;
for ( int i=0; i<5; i++ )
{
int m = post++;
int n = ++pre;
}
}
}

here is the disassembly

[c:\exper]javap -c PreIncrement
Compiled from "PreIncrement.java"
public class PreIncrement extends java.lang.Object{
public PreIncrement();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1 // post
2: iconst_0
3: istore_2 // pre
4: iconst_0
5: istore_3 // i
6: iload_3
7: iconst_5
8: if_icmpge 29
11: iload_1 // load post
12: iinc 1, 1 // inc post
15: istore 4 // store m

17: iinc 2, 1 // inc pre
20: iload_2 // load pre
21: istore 5 // store n

23: iinc 3, 1
26: goto 6
29: return

So at the byte code level, they have the same code, only slightly
different order. Comments added are mine. JavaP has no idea what
local variables are named. They are not recorded in the class file.
 
R

Roedy Green

Neither one is faster in java, since code generated for
"i++", "++i", "i += 1" and "i = i + 1" is exactly same.

same number and types of instructions, but different order. See the
Javap dissassebly in my other post.
 
B

Benji

Roedy said:
same number and types of instructions, but different order. See the
Javap dissassebly in my other post.

and, chances are that either
o the order doesn't matter, or
o the VM would generate the same native code when it compiled the
loading class.

(at least with

i++;

vs.

++i;)

if you actually use it as an expression inside of a mathematical
operation, all bets are off, because you're actually doing something
different. But still...worry more about readability than speed.
You should generally not be using an increment operator inside of an
expression. Even if it's easy for you to understand...it may not be
for someone else reading your code.
 
T

Tim Smith

C++ uses either. But I have seen i++ (by itself) much more than i++.

I don't know about . . . simpler?

When you are using i in a statement, use the one that is appropriate, they
don't return the same value.

In C++, you have to consider the possibility of overloaded operators.
If you are doing the ++ just for the side effect of incrementing i, then
it is probably safest to use ++i, because if i is an object with an
overloaded ++ operator, then i++ logically involves making a copy of the
object. That copy is not used, and the optimizer *should* get rid of
it, but might as well play it safe and use ++i.
 
R

Roedy Green

That copy is not used, and the optimizer *should* get rid of
it, but might as well play it safe and use ++i.
does this happen even when there are no overloaded operators defined
anywhere?
 
M

Matt Atterbury

Roedy Green said:
does this happen even when there are no overloaded operators defined
anywhere?

A C++ compiler can only optimise this if the postfix increment
operator is being inlined, as otherwise it has no control over the
code.

Virtual methods/operators cannot be inlined.

So, as long as the operator is not virtual and is being inlined, it
should make no difference about whether the operator is overloaded or
not, and it is *possible* for the compiler to optimise the return
value away.

However, it is not necessarily easy for the compiler to determine how
to do this; simply removing the `return' code might not be sufficient.

m.
 
B

Bent C Dalager

In C++, you have to consider the possibility of overloaded operators.
If you are doing the ++ just for the side effect of incrementing i, then
it is probably safest to use ++i, because if i is an object with an
overloaded ++ operator, then i++ logically involves making a copy of the
object. That copy is not used, and the optimizer *should* get rid of
it, but might as well play it safe and use ++i.

IIRC, it might also have side effects that you can notice if the copy
constructor changes some global state. E.g., it might increase a
global counter that keeps track of how many objects if its kind have
been created.

Cheers
Bent D
 
T

Thomas Hawtin

Matt said:
A C++ compiler can only optimise this if the postfix increment
operator is being inlined, as otherwise it has no control over the
code.

The compiler will also need access to the relevant constructor code.
Virtual methods/operators cannot be inlined.

For many, but not all compilers. Virtual methods can be inlined in a
similar manner to HotSpot. However, it helps to have profiling data.

Tom Hawtin
 
T

Tim Tyler

In comp.lang.java.programmer Kari Ikonen said:
(e-mail address removed) wrote:

Neither one is faster in java, since code generated for
"i++", "++i", "i += 1" and "i = i + 1" is exactly same.

Of course, the bytecode generated by i++ and ++i will usually
be different from each other when those statements are used
in an expression.

As I recall, a bunch of us once did some tests to see whether

for (int x = 0; x < max; x++) {...}

....was faster than...

for (int x = max; --x >= 0; ) {...}

At the time it wasn't - despite the fewer statmenents, and the compare
with 0.

The first loop was faster. Presumably, that was an idiom the
compiler recognised better and optimised for more successfully.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top