473,395 Members | 1,870 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

for loop i++ or ++i

It's a minor thing, but I'm confused on the increment operator in a for loop.

I think most usually write:

for (int i = 0; i < something; i++)
{
....
}

But, in my book (from MSPress) it shows:

for (int i; i < something; ++i)
{
....
}
From what I remember in my readings, the ++i is supposed to be faster, performance
wise.

As far as results, they both seem to do the same thing in a loop.
In my tests, of "for (int i = 0, i < 9, ++i OR i++)", both loops iterated
from 0 to 9.

But, in reading up on the increment operator on MSDN:

++i = The result of the operation is the value of the operand after it has
been incremented.

i++ = The result of the operation is the value of the operand before it has
been incremented.

This doesn't seem to make sense. If ++i returns the value after it has been
incremented, then if i was initilized to 0, should the first loop in the
for loop have i = 1????

--Brian


Nov 17 '05 #1
6 28730
Think of your for loop in these terms. It's roughly equivalent to a while
loop and an assignment statement:

int i = 0;
while (i < 9)
{
...
i++;
}

OR

int i = 0;
while (i < 9)
{
...
++i;
}

As you can see, the increment operator occurs at the end of the while loop.
The effects on placement of ++ is more readily apparent in this example:

int i = 0;
// Assigns the value of i to j
// THEN increments i
int j = i++;
Console.WriteLine(j);

i = 0;
// Increments i, then assigns the
// value if i to j
j = ++i;
Console.WriteLine(j);

Thanks.

"Brian" <fa**@email.com> wrote in message
news:40********************@news.microsoft.com...
It's a minor thing, but I'm confused on the increment operator in a for
loop.

I think most usually write:

for (int i = 0; i < something; i++)
{
...
}

But, in my book (from MSPress) it shows:

for (int i; i < something; ++i)
{
...
}
From what I remember in my readings, the ++i is supposed to be faster,
performance wise.

As far as results, they both seem to do the same thing in a loop.
In my tests, of "for (int i = 0, i < 9, ++i OR i++)", both loops iterated
from 0 to 9.

But, in reading up on the increment operator on MSDN:

++i = The result of the operation is the value of the operand after it has
been incremented.

i++ = The result of the operation is the value of the operand before it
has been incremented.

This doesn't seem to make sense. If ++i returns the value after it has
been incremented, then if i was initilized to 0, should the first loop in
the for loop have i = 1????

--Brian

Nov 17 '05 #2
There is a difference between i++ and ++i if you **use** the value of the
expression. For example:
int j = i++;
and
int j = ++i;
will assign different values to j.

But if you put the i++ or ++i expression in the 3rd clause of the for
construct, you get a simple statement and the value that it produces in
**not used** for anything. So, there won't be any difference, not even in
performance, because the compiler will simply generate an increment
instruction and will not worry about the value produced by the expression.

Bruno

"Brian" <fa**@email.com> a écrit dans le message de news:
40********************@news.microsoft.com...
It's a minor thing, but I'm confused on the increment operator in a for
loop.

I think most usually write:

for (int i = 0; i < something; i++)
{
...
}

But, in my book (from MSPress) it shows:

for (int i; i < something; ++i)
{
...
}
From what I remember in my readings, the ++i is supposed to be faster,
performance wise.

As far as results, they both seem to do the same thing in a loop.
In my tests, of "for (int i = 0, i < 9, ++i OR i++)", both loops iterated
from 0 to 9.

But, in reading up on the increment operator on MSDN:

++i = The result of the operation is the value of the operand after it has
been incremented.

i++ = The result of the operation is the value of the operand before it
has been incremented.

This doesn't seem to make sense. If ++i returns the value after it has
been incremented, then if i was initilized to 0, should the first loop in
the for loop have i = 1????

--Brian

Nov 17 '05 #3
Thanks,

That makes sense.

B
Think of your for loop in these terms. It's roughly equivalent to a
while loop and an assignment statement:

int i = 0;
while (i < 9)
{
...
i++;
}
OR

int i = 0;
while (i < 9)
{
...
++i;
}
As you can see, the increment operator occurs at the end of the while
loop. The effects on placement of ++ is more readily apparent in this
example:

int i = 0;
// Assigns the value of i to j
// THEN increments i
int j = i++;
Console.WriteLine(j);
i = 0;
// Increments i, then assigns the
// value if i to j
j = ++i;
Console.WriteLine(j);
Thanks.

"Brian" <fa**@email.com> wrote in message
news:40********************@news.microsoft.com...
It's a minor thing, but I'm confused on the increment operator in a
for loop.

I think most usually write:

for (int i = 0; i < something; i++)
{
...
}
But, in my book (from MSPress) it shows:

for (int i; i < something; ++i)
{
...
}
From what I remember in my readings, the ++i is supposed to be
faster, performance wise.

As far as results, they both seem to do the same thing in a loop.
In my tests, of "for (int i = 0, i < 9, ++i OR i++)", both loops
iterated
from 0 to 9.
But, in reading up on the increment operator on MSDN:

++i = The result of the operation is the value of the operand after
it has been incremented.

i++ = The result of the operation is the value of the operand before
it has been incremented.

This doesn't seem to make sense. If ++i returns the value after it
has been incremented, then if i was initilized to 0, should the first
loop in the for loop have i = 1????

--Brian


Nov 17 '05 #4
> From what I remember in my readings, the ++i is supposed to be faster,
performance

I too have read about this performance gain when you use the
pre-incrementor. However, everyone I've talked to since has said it was
hogwash. Unfortunately I don't have the article handy for reference. :<
And that was when I was learning C++, so maybe in the C# world this
performance gain has been incorporated in/out of the JIT and may no longer
be applicable?

Can any JIT gurus comment?
Nov 17 '05 #5
Flip wrote:

I won't comment on the semantic equivalence of "++i" and "i++" in
for-loops, other posters have done that, but try to explain *why*
postfix increment may be considered "more expensive".

Try to think of is as:

class Foo {
Foo(Foo other) { this.state = other.state; } // copy-constructor
private void increment();
static Foo prefix_increment(Foo foo);
static Foo postfix_increment(Foo foo);
}

Now, prefix_increment should return a Foo in an incremented state, and
leave the "foo" argument in an incremented state -- how convinient:

static Foo prefix_increment(Foo foo) { foo.increment(); return foo; }

But what about the postfix one? well it needs to return an object in the
same state as "foo", but increment the state of "foo", there really only
is one solution:

static Foo postfix_increment(Foo foo) {
Foo ret = new Foo(foo);
foo.increment();
return ret;
}

This requires copying the state of foo to another Foo-instance!

C++ compilers are quite good at removing this overhead -- so there
really isn't much difference, except that "++i" will never incur the
overhead. If i is an "int" i doubt *very* much that you would ever see
any performance difference.

Especially, compilers can often simply the code around:

f(i++);

Is intentionally (except in the process of overloading resolution --
atleast in c++, dunno about C#) equivalent to

f(i); ++i;

But the latter form may be inconvinient for the programmer: it is not
one statement, and therefore fits badly into sytax that requires a block
or single statement: if, for, ... requiering another set of braces (and
if you are using the on-crack convention of braces on newlines: 2 more
lines of confusion :)
Can any JIT gurus comment?


I am definatly not a JIT guru, but I have crossed swords with a lot of
c++ in my time :)

Anyway, if you ever have a performance-problem due to
postfix-incrementing-by-convention I'd like to see it.

But, when you know the issue, you tend to write "++i" instead of "i++"
-- just because it feels better and doesn't cost a thing.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #6
"Flip" <[remove_me]ph******@hotmail.com> wrote in message
news:uR**************@TK2MSFTNGP09.phx.gbl...
From what I remember in my readings, the ++i is supposed to be faster,
performance

I too have read about this performance gain when you use the
pre-incrementor. However, everyone I've talked to since has said it was
hogwash. Unfortunately I don't have the article handy for reference. :<
And that was when I was learning C++, so maybe in the C# world this
performance gain has been incorporated in/out of the JIT and may no longer
be applicable?

Can any JIT gurus comment?


Can't speak to JIT on C# for that one, but in x86 Assembler-speak, you're
looking at roughly this (in these examples -- very, very simplified -- AX
represents a register and [i] and [j] represent memory locations for i and j
integer variables):

"j = ++i" would roughly be equivalent to:

MOV AX, [i]
INC AX
MOV [i], AX
MOV [j], AX

"j = i++" would be roughly equivalent to:

MOV AX, [i]
MOV [j], AX
INC AX
MOV [i], AX

Although the compiler might be able to further optimize to take advantage of
various other instructions, we're looking at basically the same instructions
just in a slightly different order. And this is just for an integer data
type. For other data types, especially objects, there's a lot more moving
and copying of data between memory locations than with a standard integer.
Helge spoke to that.

So basically, for an integer data type, there's really no difference between
the instructions ++i and i++ generate - just the order they are generated
in. So your performance should not be affected one way or the other
depending on which you use; the results of your calculations, however, can
be affected wildly; so use them in calculations carefully.

---

As a side note: For a compiler that didn't optimize well, "i = i + 1; j =
i" might end up generating something like this:

MOV AX, [i]
ADD AX, 1
MOV [i], AX
MOV [j], AX

This would be less efficient because the non-optimizing compiler translated
our code literally, and replaced i + 1 with an ADD instruction. The ADD
instruction takes up more memory and executes more slowly than the INC
instruction. Most compilers are smart enough to convert j = i + 1 to an INC
instruction, however.
Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Charles Alexander | last post by:
Hello I am new to php & MySQL - I am trying to retrieve some records from a MySQL table and redisplay them. The data in list form looks like this: Sample_ID Marker_ID Variation ...
3
by: Anand Pillai | last post by:
This is for folks who are familiar with asynchronous event handling in Python using the asyncore module. If you have ever used the asyncore module, you will realize that it's event loop does not...
43
by: Gremlin | last post by:
If you are not familiar with the halting problem, I will not go into it in detail but it states that it is impossible to write a program that can tell if a loop is infinite or not. This is a...
5
by: Martin Schou | last post by:
Please ignore the extreme simplicity of the task :-) I'm new to C, which explains why I'm doing an exercise like this. In the following tripple nested loop: int digit1 = 1; int digit2 = 0;...
32
by: Toby Newman | last post by:
At the page: http://www.strath.ac.uk/IT/Docs/Ccourse/subsection3_8_3.html#SECTION0008300000000000000 or http://tinyurl.com/4ptzs the author warns: "The for loop is frequently used, usually...
2
by: Alex | last post by:
Compiler - Borland C++ 5.6.4 for Win32 Copyright (c) 1993, 2002 Borland Linker - Turbo Incremental Link 5.65 Copyright (c) 1997-2002 Borland Platform - Win32 (XP) Quite by accident I stumbled...
3
by: Ben R. | last post by:
In an article I was reading (http://www.ftponline.com/vsm/2005_06/magazine/columns/desktopdeveloper/), I read the following: "The ending condition of a VB.NET for loop is evaluated only once,...
32
by: cj | last post by:
When I'm inside a do while loop sometimes it's necessary to jump out of the loop using exit do. I'm also used to being able to jump back and begin the loop again. Not sure which language my...
16
by: Claudio Grondi | last post by:
Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of...
2
ADezii
by: ADezii | last post by:
If you are executing a code segment for a fixed number of iterations, always use a For...Next Loop instead of a Do...Loop, since it is significantly faster. Each pass through a Do...Loop that...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.