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.