Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

++i or i++ in for loops ?? [duplicate]

Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?

Is there a reason some programmers write ++i in a normal for loop instead of writing i++?

like image 540
Ismail Marmoush Avatar asked Nov 23 '10 22:11

Ismail Marmoush


People also ask

Why is there an I in for loop?

Nothing, its just a local variable. You could call it just about anything you wanted and use that name in your loop instead.

How do you remove duplicates from a loop in Python?

You can make use of a for-loop that we will traverse the list of items to remove duplicates. The method unique() from Numpy module can help us remove duplicate from the list given. The Pandas module has a unique() method that will give us the unique elements from the list given.

What is the value of I in for loop in Python?

Technical Note: In the C programming language, i++ increments the variable i . It is roughly equivalent to i += 1 in Python.

Can we use == in for loop?

A for loop runs while the condition is true... You can use == but you can iterate max one time.


2 Answers

++i is slightly more efficient due to its semantics:

++i;  // Fetch i, increment it, and return it i++;  // Fetch i, copy it, increment i, return copy 

For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the loop body doesn't contain much work).

As an example, consider the following loop using a theoretical BigInteger class providing arbitrary precision integers (and thus some sort of vector-like internals):

std::vector<BigInteger> vec; for (BigInteger i = 0; i < 99999999L; i++) {   vec.push_back(i); } 

That i++ operation includes copy construction (i.e. operator new, digit-by-digit copy) and destruction (operator delete) for a loop that won't do anything more than essentially make one more copy of the index object. Essentially you've doubled the work to be done (and increased memory fragmentation most likely) by simply using the postfix increment where prefix would have been sufficient.

like image 51
Drew Hall Avatar answered Sep 20 '22 18:09

Drew Hall


For integers, there is no difference between pre- and post-increment.

If i is an object of a non-trivial class, then ++i is generally preferred, because the object is modified and then evaluated, whereas i++ modifies after evaluation, so requires a copy to be made.

like image 41
Oliver Charlesworth Avatar answered Sep 18 '22 18:09

Oliver Charlesworth