473,770 Members | 6,348 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creation of temporary objects in loop

Which is more efficient (if either)

[Pseudo code]
MyHugeClass MyObject;
for ( int i = 0; i < 1000; ++i )
{
MyObject = SomeVal[i];
Use MyObject;
}

or

for ( int i = 0; i < 1000; ++i )
{
MyHugeClass MyObject = SomeVal[i];
Use MyObject;
}

That is, if I declare MyObject inside a for loop, does it get recreated
each iteration, or does the compiler create it once and reuse each time?

Or is it UB?

Jul 23 '05
14 1670
Jim Langston wrote:
Which is more efficient (if either)


You might get more accurate results by measuring it, rather than asking
here. It depends on many properites of your class and how you use it
(do the constructor/destructor do anything, is it modified while being
used, etc.). Here is my test program:
#include <vector>
#include <numeric>

using namespace std;

class HugeObject: public vector<int> {
public:
HugeObject(): vector<int>(500 00) {}
};

void use(HugeObject& h)
{
int t = accumulate(h.be gin(),h.end(),0 );
srand(t);
}

int main(int argc, char* argv[])
{
vector<HugeObje ct> SomeVals(1000);

for(int i=0; i<1000; ++i) {
HugeObject h = SomeVals[i];
use(h);
}
}

Platform: Linux, celeron-500, enough RAM, gcc-3.4, -O9.

real 0m8.916s
user 0m5.408s
sys 0m3.315s

Move the HugeObject h declaration outside the loop:

real 0m8.732s
user 0m6.597s
sys 0m1.969s

(Less system time probably means it spent less time doing low-level
memory allocation, presumably because it allocated in larger chunks.
But it makes up for that with more user time, for some reason. The
overall difference is not significant.)

Put the declaration back inside the loop but make it a reference. You
can only do this if you are not going to modify the copy, or don't mind
SomeVal also being changed:

real 0m5.427s
user 0m3.348s
sys 0m1.948s

Somewhat better.

But none of these are really significant differences. If you are
worried about the efficiency of your application you should be looking
for big-O complexity reduction, not this sort of change.

--Phil.
Jul 23 '05 #11
I suppose I have to ask the question why you're doing this sort of loop
?
Hard to tell whether it's necessary, or whether you might be better off
dealing with
references/pointers.
Worth also suggesting that you might consider a const ref to the
object. This provides a strong hint to the compiler about how it might
optimise the code.

DominiConnor
Quant Headhunter

Jul 23 '05 #12
Alf P. Steinbach wrote:
In general: it's not a good idea to worry about execution efficiency in
cases where you suspect the compiler might be able to do something.


In general: it's not a good idea to suspect the compiler might be able to do
something. If speed is not a concern, just ignore it, but don't assume
anthing about the optimization behavior. If speed is a concern, measure the
performance and maybe have a look at the generated code.

Jul 23 '05 #13
Rene Moehring wrote:
On Mon, 20 Jun 2005 11:30:27 +1000, ben wrote:

"Jim Langston" <ta*******@rock etmail.com> wrote in message
news:wS******** *********@fe05. lga...
Which is more efficient (if either)

[Pseudo code]
MyHugeClass MyObject;
for ( int i = 0; i < 1000; ++i )
{
MyObject = SomeVal[i];
Use MyObject;
}

or

for ( int i = 0; i < 1000; ++i )
{
MyHugeClass MyObject = SomeVal[i];
Use MyObject;
}
It depends. But in most cases the first case will be more efficient
because the assignment is usually lighter than a copy constructor.


Besides the fact that no copy ctor is used.


Wrong. The second example uses a copy constructor to create a fresh copy of
SomeVal[i].
How can assigning be cheaper than a copy? The assignment in the first case
is a copy.


The object might need some initialization work that is done in the
constructor, but doesn't need to be redone in the assignment operator,
because the object is already constructed.

Jul 23 '05 #14
* Rolf Magnus:
Alf P. Steinbach wrote:
In general: it's not a good idea to worry about execution efficiency in
cases where you suspect the compiler might be able to do something.
In general: it's not a good idea to suspect the compiler might be able to do
something.


That's folly.

And it's an attempt at countering something else than you replied to.

If speed is not a concern, just ignore it, but don't assume
anthing about the optimization behavior. If speed is a concern, measure the
performance and maybe have a look at the generated code.


That's good.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #15

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

Similar topics

12
1567
by: possibilitybox | last post by:
this code here: def wordcount(lines): for i in range(len(lines)/8): words = lines.split(" ") if not locals().has_key("frequency"): frequency = {} for word in words: if frequency.has_key(word):
1
1514
by: chettiar | last post by:
Hi, I am dropping an index and recreating it to lower the high water mark. The index creation is taking a lot of time. I am stuck as to why it does so. Is there any way that I can find out why it is doing so. Is there a snapshot that will help me while index creation. P.S. There are no users connected to the system when i m creating the index.
8
1249
by: Lee Jackson | last post by:
Whats the difference between the following in terms of how the CLR allocates and garbage collects? Which is better in terms of memory usage/performance? a) foreach (string strURL in arrLongListOfURLs) { string strCopy = strURL; }
17
10283
by: Henning Hasemann | last post by:
I have a function which gets the adress of an object as argument. It does some comparsion with the object's contents and then returns. no Reference or pointer to the object is stored or will be used after the function has returned. Say the function whould be named f and the objects class whould be T it'll look like this: bool f(T* thing) { return thing->foobar == 5; // Just a stupid example
7
1670
by: xllx.relient.xllx | last post by:
Q1: What happens when you apply parenthesis to the class type name? Is the constructor for the class called and returns an object?, or what? in main...: MyClass(); // end
6
1862
by: tomthemighty | last post by:
A simple RAII wrapper for acquiring a Thingy that has two alternative acquire methods, acquire() and acquireAndFurtle(): class ThingyAcquirer : private boost::noncopyable { public: explicit ThingyAcquirer (Thingy& thingy, bool furtle = false) : mThingy(thingy) { if(furtle)
1
1490
by: sachingoel82 | last post by:
Hi All, I find following C++ behaviour regarding temporary objects quite contradictory. Consider this: class A { ... public:
9
1304
by: Rahul | last post by:
Hi Everyone, class Base { public : Base(int i) { printf("constructor\n"); } void disp() {
31
3415
by: Tom P. | last post by:
I am doing quite a bit of custom painting and it means I have to create a lot of brushes (think one for every file system object in a directory) per paint. How expensive is this? Should I find a way to create the brushes once, store them in an member variable, and use them when I need them? Or is creating brushes a throw-away process that doesn't take a lot of work? Thanks for the info. Tom P.
0
9425
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10225
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10053
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...
0
9867
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8880
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
7415
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
6676
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
5312
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...
1
3969
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

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.