473,761 Members | 8,933 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 #1
14 1664
* Jim Langston:
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;
}


In terms of execution time: depends on the object, so if it turns out
to be critical, measure.

In terms of programmer time: the first is often hugely more efficient.

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.

--
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 #2
ben

"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. But also consider
ausing reference:

for (int = 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?
yes, it is not only recreated but also destroyed each iteration.

Or is it UB?

Jul 23 '05 #3
* Alf P. Steinbach:
* Jim Langston:
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;
}
In terms of execution time: depends on the object, so if it turns out
to be critical, measure.

In terms of programmer time: the first is often hugely more efficient.


I meant the _second_, of course.

"Resetting" an object is often difficult and makes it difficult to rely
on anything about the object state.

An exception is where an object has a natural default state such as an
empty string or empty vector, but even there the cost of construction
+ destruction, relative to assignment/reset, is typically negligible.

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.


--
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 #4
Jim Langston wrote:
Which is more efficient (if either) [Pseudo code]

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

or

MyHugeClass MyObject;
for (int i = 0; i < 1000; ++i) {
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?


The first form is always preferred over the second above
because it confines MyObject to the narrowest scope.

The assignment operator is often more expensive
than the copy constructor/destructor combination.

A good optimizing C++ compiler will automatically
"boost" the storage allocation for MyObject up out of the loop and,
if the copy constructor and destructor can be inline'd,
it will optimize away unnecessary overhead.

Avoid premature optimization.
Use your profiler to locate performance bottlenecks.
Don't even consider the second option
unless you can demonstrate that the first is causing problems.
Jul 23 '05 #5
al***@start.no (Alf P. Steinbach) wrote in news:42b61b7c.1 32200562
@news.individua l.net:
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?


I have to remember this one
Jul 23 '05 #6
The second will be much more efficient since the compiler can optimize
that code quite a lot.

MyObject o = getObject ();

Here the temporary can be taken as 'o' so this is often even more
efficient that to get the objetct by reference.

regards

Rob

Jul 23 '05 #7
ben
You had the first and second code snippet swapped!

ben
Jul 23 '05 #8
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. How can assigning be cheaper
than a copy? The assignment in the first case is a copy.
But also consider
ausing reference:

for (int = 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?


yes, it is not only recreated but also destroyed each iteration.

Or is it UB?


--
I'm not a racist. I hate everyone equally!
Jul 23 '05 #9


E. Robert Tisdale schreef:
Jim Langston wrote:
for (int i = 0; i < 1000; ++i) {
MyHugeClass MyObject = SomeVal[i];
// Use MyObject;
}

A good optimizing C++ compiler will automatically
"boost" the storage allocation for MyObject up out of the loop and,
if the copy constructor and destructor can be inline'd,
it will optimize away unnecessary overhead.


The common term is to "hoist" the allocation. However, often all
allocations are done at once when the function is called. Allocating
storage is simply a matter of incrementing the stack pointer and
using that stackframe. It's trivial to see that __sp+=4;__sp+=4 ; can
be optimized to __sp+=8;. Hence, the term "hoisting" is more commonly
applied to "hoisting" the evaluation of constant expression, i.e.

int offset = foo();
for (int i = 0; i < 1000; ++i) {
MyHugeClass MyObject = SomeVal[2* offset + i];
}
Here, (2*offset) can be hoisted.

HTH,
Michiel Salters

Jul 23 '05 #10

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
10282
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
1860
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
1303
by: Rahul | last post by:
Hi Everyone, class Base { public : Base(int i) { printf("constructor\n"); } void disp() {
31
3414
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
9988
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
9923
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
9811
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
8813
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
7358
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
6640
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
5266
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
3911
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
3
3509
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.