473,804 Members | 3,526 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

i++ , or ++i, which is faster?

"the c++ standard library, tutorial and reference" book, it says:

++i is faster than i++. the latter involves a temporary object because
it must return the old value/object of i. for this reason, it's
generally better to use ++i.

but, I think, even ++i still has to return a temporary object that is
with new value inside. So, both i++ and ++i have to return a temporary
object. Then, what's the speed difference between i++ and ++i.

Jul 23 '05 #1
29 3287

<gu******@gmail .com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
"the c++ standard library, tutorial and reference" book, it says:

++i is faster than i++. the latter involves a temporary object because
it must return the old value/object of i. for this reason, it's
generally better to use ++i.

but, I think, even ++i still has to return a temporary object that is
with new value inside. So, both i++ and ++i have to return a temporary
object. Then, what's the speed difference between i++ and ++i.


The prefix version returns by reference, so no temporary copy is needed.

-Howard
Jul 23 '05 #2

<gu******@gmail .com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
"the c++ standard library, tutorial and reference" book, it says:

++i is faster than i++. the latter involves a temporary object because
it must return the old value/object of i. for this reason, it's
generally better to use ++i.

but, I think, even ++i still has to return a temporary object that is
with new value inside. So, both i++ and ++i have to return a temporary
object. Then, what's the speed difference between i++ and ++i.


I'm still learning C/C++, but the chapter I just finished dealt with
overloading operators, including postfix and prefix increment/decrement.
According to my understanding and the assignment I did, the prefix
increment/decrement, ++i in your example, increases the value of the object,
and then returns it. The postfix increment/decrement, i++ in your example,
copies the current value of the object, increases the current value of the
object, and returns the value of the copy. Thus, prefix only has two steps,
where postfix has three.

Is my interpretation correct?

Dave
Jul 23 '05 #3
gu******@gmail. com wrote:
"the c++ standard library, tutorial and reference" book, it says:

++i is faster than i++. the latter involves a temporary object because
it must return the old value/object of i. for this reason, it's
generally better to use ++i.

but, I think, even ++i still has to return a temporary object that is
with new value inside. So, both i++ and ++i have to return a temporary
object. Then, what's the speed difference between i++ and ++i.


No, I think ++i returns a reference to i. ++i returns a new object
containing the old value of i. For primitive types, the speed
difference negligible. But, if you wrote a class that allocated 10
megabytes of memory for each instance, the difference would be huge.

Kristo

Jul 23 '05 #4
gu******@gmail. com wrote:
"the c++ standard library, tutorial and reference" book, it says:

++i is faster than i++. the latter involves a temporary object because
it must return the old value/object of i. for this reason, it's
generally better to use ++i.

but, I think, even ++i still has to return a temporary object that is
with new value inside. So, both i++ and ++i have to return a temporary
object. Then, what's the speed difference between i++ and ++i.


This is an abomination, uh, I mean to say class, I created that demonstrates
the difference rather well. Notice that in the postfix case I have to
check to see if there is a temporary object, create it if it doesn't exist,
and assign to it if it does exits. In the prefix form, there is no need to
deal with the temporary object, so there are fewer instructions executed
per call.

I didn't see an obvious way of moving the creation of the temporary object
into constructor since that would lead to unbounded recursion. I could
probably be done by passing some kind of flag to a special constructor.
That might marginally improve performance, but will not make the postfix
form as efficient as the prefix form. Also be aware that I have not tested
the version presented here in so much as it derives from the
util::Reference d baseclass. Additionally, I am less than fully comfortable
with the choice of wrapping the index at the bounds. It does not follow
STL semantics for iterators, and adds a bit of overhead with the '%'
operations.

/*************** *************** *************** *************** ***************
* Copyright (C) 2005 by Steven T. Hatton *
* ha*****@globals ymmetry.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *

*************** *************** *************** *************** ***************/
#ifndef MATH_BOUNDEDIND EX_H
#define MATH_BOUNDEDIND EX_H

#include <util/Referenced.h>

namespace math {

/*!\brief The BoundedIndex class provides an \c unsigned \c int in the
range \e [0,supremum)

BoundedIndex represents an \c unsigned \c int ragning from \c 0 \e
inclusive
to \c supremum \e exclusive. It provides both C-style increment and
decrement operators (++,--)
as well as Java-style iterator functions (next(), hasNext()) with
bidirectional functionality.
When the value is incremented beyond either bound, it wraps to the
opposing end of the range.
*/
class BoundedIndex: public util::Reference d {
public:

/*!
Constructor creates 0 range index. Intended to support collection
construction;
*/
BoundedIndex()
:_index(0)
,_sup(0)
,_tmp_ptr(0)
{}

/*!
Constructor
The index value is initialized to 0.
\param sup_ value of \c supremum \e exclusive.
*/
explicit BoundedIndex(un signed sup_)
:_index(0)
,_sup(sup_)
,_tmp_ptr(0)
{}

/*!
Copy Constructor copies both \c index and \c supremum.
*/
BoundedIndex(co nst BoundedIndex& b)
:_index(b._inde x)
,_sup(b._sup)
,_tmp_ptr(0)
{}

/*!
Assignment Operator copies both \c index and \c supremum.
*/
BoundedIndex& operator=(const BoundedIndex& b) {
if(b == *this) return *this;
_sup = b._sup;
_index = b._index;
_tmp_ptr = 0;
}

/*!
Assignment operator clamps \c index to \e [0,supremum)
\param index_ The new index value before clamping.
*/
BoundedIndex& operator=(const unsigned& index_) {
_index = index_ % _sup;
return *this;
}

/*!
Conversion operator converts to \c unsigned \c int.
*/
operator unsigned () const { return _index; }

/*!
Prefix increment operator
*/
BoundedIndex& operator++() {
_index = (_index + 1) % _sup;
return *this;
}

/*!
Postfix increment operator
*/
const BoundedIndex& operator++(int) {
if(!_tmp_ptr) _tmp_ptr = new BoundedIndex(*t his); else
_tmp_ptr->_index = _index;
_index = (_index + 1) % _sup;
return *_tmp_ptr;
}

/*!
Prefix decrement operator
*/
const BoundedIndex& operator--() {
_index = _index < 1 ? _sup - 1: _index - 1;
return *this;
}

/*!
Postfix decrement operator
\return reference to a temporary copy of this.
*/
BoundedIndex& operator--(int) {
if(!_tmp_ptr) _tmp_ptr = new BoundedIndex(*t his); else
_tmp_ptr->_index = _index;
_index = (_index + 1) % _sup;
return *_tmp_ptr;
}

/*!
Compund assignment addition operator.
\return reference to this.
*/
BoundedIndex& operator+=(cons t unsigned& di_) {
_index = (_index + di_)%_sup;
return *this;
}

/*!
Compund assignment subtraction operator.
\return reference to this.
*/
BoundedIndex& operator-=(const unsigned& di_) {
_index = _index >= di_? (_index - di_): _sup - (di_ - _index)%_sup;
return *this;
}

/*!
Accessor
\return value of \c supremum
*/
unsigned sup() const { return _sup; }

/*!
Mutator
\param sup_ set the value of \c supremum.
*/
void sup(unsigned sup_ ) { _sup = sup_; }

/*!
Accessor
\return value of \c index
*/
unsigned index() const { return _index; }

/*!
Mutator
\param index_ set the value of \c index.
*/
void index(unsigned index_ ) { _index = index_; }

/*!
Tests whether the index can be increased;
*/
bool hasNext() const { return _index < _sup - 1; }

/*!
Tests whether the index can be decreased;
*/
bool hasPrevious() const { return _index > 0; }

/*!
Wrapper for operator++();
*/
BoundedIndex& next() { return operator++(); }

/*!
Wrapper for operator--();
*/
BoundedIndex& previous() { return operator--(); }

protected:
/*!
Destructor.
*/
~BoundedIndex() { delete _tmp_ptr; }

private:
unsigned _index;
unsigned _sup;
BoundedIndex* _tmp_ptr;
};

/*!
BoundedIndex binary addition operator;
*/
BoundedIndex operator+(const BoundedIndex& arg1, const BoundedIndex& arg2)
{
BoundedIndex ret(arg1);
return ret += arg2;
}

/*!
BoundedIndex binary subtraction operator;
*/
BoundedIndex operator-(const BoundedIndex& arg1, const BoundedIndex& arg2)
{
BoundedIndex ret(arg1);
return ret -= arg2;
}
}
#endif

--
If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true.-Bertrand Russell
Jul 23 '05 #5
I see, thanks!

i++ is:

template<class T>
T foo (T& i) {
T temp(i);
i = i+1;
return temp;
}

++i is:
template<class T>
T& foo(T& i) {
i = i+1;
return i; }

Howard wrote:
<gu******@gmail .com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
"the c++ standard library, tutorial and reference" book, it says:

++i is faster than i++. the latter involves a temporary object because
it must return the old value/object of i. for this reason, it's
generally better to use ++i.

but, I think, even ++i still has to return a temporary object that is
with new value inside. So, both i++ and ++i have to return a temporary
object. Then, what's the speed difference between i++ and ++i.


The prefix version returns by reference, so no temporary copy is needed.

-Howard


Jul 23 '05 #6
> /*!
Prefix increment operator
*/
BoundedIndex& operator++() {
_index = (_index + 1) % _sup;
return *this;
}

/*!
Postfix increment operator
*/
const BoundedIndex& operator++(int) {
if(!_tmp_ptr) _tmp_ptr = new BoundedIndex(*t his); else
_tmp_ptr->_index = _index;
_index = (_index + 1) % _sup;
return *_tmp_ptr;
}


Thanks!

Jul 23 '05 #7
Kristo wrote:
gu******@gmail. com wrote:
"the c++ standard library, tutorial and reference" book, it says:

++i is faster than i++. the latter involves a temporary object because
it must return the old value/object of i. for this reason, it's
generally better to use ++i.

but, I think, even ++i still has to return a temporary object that is
with new value inside. So, both i++ and ++i have to return a temporary
object. Then, what's the speed difference between i++ and ++i.

No, I think ++i returns a reference to i.

++i
You meant 'i++'...
returns a new object
containing the old value of i. For primitive types, the speed
difference negligible. But, if you wrote a class that allocated 10
megabytes of memory for each instance, the difference would be huge.


I just wonder why is everybody in a rush to type up an answer to a FAQ
that is actually in _the_FAQ_ (and make a few typos on the way)?...

I am really puzzled by it. Honestly.

V
Jul 23 '05 #8

Please don't top-post. I've re-arranged things properly below:
Howard wrote:
<gu******@gmail .com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
> "the c++ standard library, tutorial and reference" book, it says:
>
> ++i is faster than i++. the latter involves a temporary object because
> it must return the old value/object of i. for this reason, it's
> generally better to use ++i.
>
> but, I think, even ++i still has to return a temporary object that is
> with new value inside. So, both i++ and ++i have to return a temporary
> object. Then, what's the speed difference between i++ and ++i.
>


The prefix version returns by reference, so no temporary copy is needed.

-Howard
<gu******@gmail .com> wrote in messageI see, thanks!


i++ is:

template<class T>
T foo (T& i) {
T temp(i);
i = i+1;
return temp;
}

++i is:
template<class T>
T& foo(T& i) {
i = i+1;
return i; }


Where did you get those? That's not how they're implemented at all. A
proper prefix increment (or decrement) operator returns *this, a reference
to the current object. What you've shown is returning a reference to a
local object, which is not valid because the object goes out of scope at the
end of the function. Also, the function signatures are incorrect.

I suggest you get a better book.

-Howard


Jul 23 '05 #9
Howard wrote:
<gu******@gmail .com> wrote in message
I see, thanks!
i++ is:

template<clas s T>
T foo (T& i) {
T temp(i);
i = i+1;
return temp;
}

++i is:
template<clas s T>
T& foo(T& i) {
i = i+1;
return i; }

Where did you get those? That's not how they're implemented at all. A
proper prefix increment (or decrement) operator returns *this, a reference
to the current object. What you've shown is returning a reference to a
local object, which is not valid because the object goes out of scope at the
end of the function. Also, the function signatures are incorrect.


You seem to presume that the functions are members. There is no such
requirement. The 'foo' things here are stand-alone functions, just
showing the semantics of post- and pre-increment.
I suggest you get a better book.


What if you do, as well?

V
Jul 23 '05 #10

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

Similar topics

36
2660
by: Armin Rigo | last post by:
Hi! This is a rant against the optimization trend of the Python interpreter. Sorting a list of 100000 integers in random order takes: * 0.75 seconds in Python 2.1 * 0.51 seconds in Python 2.2 * 0.46 seconds in Python 2.3
23
4763
by: YinTat | last post by:
Hi, I learned C++ recently and I made a string class. A code example is this: class CString { public: inline CString(const char *rhs) { m_size = strlen(rhs);
98
14467
by: jrefactors | last post by:
I heard people saying prefix increment is faster than postfix incerement, but I don't know what's the difference. They both are i = i+1. i++ ++i Please advise. thanks!!
65
12634
by: Skybuck Flying | last post by:
Hi, I needed a method to determine if a point was on a line segment in 2D. So I googled for some help and so far I have evaluated two methods. The first method was only a formula, the second method was a piece of C code which turned out to be incorrect and incomplete but by modifieing it would still be usuable. The first method was this piece of text:
1
2731
by: James dean | last post by:
I done a test and i really do not know the reason why a jagged array who has the same number of elements as a multidimensional array is faster here is my test. I assign a value and do a small calculation. Even if i initialise the jagged array inside the function it is still much faster. Are these results correct?. If i put the initialisation loop in the constructor its ridiculously faster but even here its 4 times faster...is this correct?...
9
5165
by: VenuGopal | last post by:
Hi, why n++ executes faster than n+1..... or does it realli execute faster? thanks Venugopal.B
11
2999
by: ctman770 | last post by:
Hi Everyone, Is it faster to save the precise location of an html dom node into a variable in js, or to use getElementById everytime you need to access the node? I want to make my application as fast as possible. I have about 10-20 id tags that need to be accessed and modified from time to time. Would the jvm perform slowly if I stored all of the dom node strings "document.node.child...." into a huge js array?
12
9411
by: karthikbalaguru | last post by:
Hi, How is 'Int' Faster than 'Char' ? I think , 'Char' is small and so it should be easily & efficiently . Can someone here provide some info regarding this. Thanks and Regards, Karthik Balaguru
23
2538
by: Python Maniac | last post by:
I am new to Python however I would like some feedback from those who know more about Python than I do at this time. def scrambleLine(line): s = '' for c in line: s += chr(ord(c) | 0x80) return s def descrambleLine(line):
41
2718
by: c | last post by:
Hi every one, Me and my Cousin were talking about C and C#, I love C and he loves C#..and were talking C is ...blah blah...C# is Blah Blah ...etc and then we decided to write a program that will calculate the factorial of 10, 10 millions time and print the reusult in a file with the name log.txt.. I wrote something like this
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10327
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9161
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7625
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4302
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.