473,657 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Repeated instantiation of a variable / performance?

// Code sequence A
for (int i = 0; i < 10; ++i) {
int k = something();
// some more code which uses k
}

// Code sequence B
int k;
for (int i = 0; i < 10; ++i) {
k = something();
// some more code which uses k
}

Are the two sequences exactly the same in terms of performance, or has the
repeated instanciation of k in sequence A a certain cost compared with the
single one instantiation in sequence B?
What about if k were of a class type?
Thanks, Robert
Jul 22 '05 #1
15 1502
On Fri, 2 Jul 2004 06:24:47 +0200, Robert Sturzenegger
<yo************ **@ziksuhy.ch> wrote:
// Code sequence A
for (int i = 0; i < 10; ++i) {
int k = something();
// some more code which uses k
}

// Code sequence B
int k;
for (int i = 0; i < 10; ++i) {
k = something();
// some more code which uses k
}

Are the two sequences exactly the same in terms of performance, or has
the
repeated instanciation of k in sequence A a certain cost compared with
the
single one instantiation in sequence B?
What about if k were of a class type?
Thanks, Robert


Who can say? One compiler could be different from the next. If you are
really interested then write the program and time it (or look at the
generated machine code). Personally I would be surprised to see any
difference, but then I've never really looked into it.

As for the class version then it depends upon the class (and on the
compiler). You are comparing the cost of assignment with the cost of copy
construction. Which is more efficient depends entirely on how the class is
written, There is no a priori reason to expect either to be more efficient.

john
Jul 22 '05 #2
> // Code sequence A
for (int i = 0; i < 10; ++i) {
int k = something();
// some more code which uses k
}

// Code sequence B
int k;
for (int i = 0; i < 10; ++i) {
k = something();
// some more code which uses k
}

Are the two sequences exactly the same in terms of performance, or has the
repeated instanciation of k in sequence A a certain cost compared with the
single one instantiation in sequence B?
The compilers I have used (Borland, Microsoft) on Windows do allocate the
space for k when the function starts. Actually there is an x86 assembly
instruction for that, so you can assume that all wellwritten compilers do
that. So for simple types there will be no difference.
What about if k were of a class type?


As John mentions the first is a construction and the second an assignment.
Some classes will do the same in those cases. Others will do some more
initialization in the construction case. A few might do more work in the
assignment case.
I would prefer the construction case because of clarity caused by the
limited scope, unless I know for sure that the construction of the object is
much more expensive than an assignment.

Niels Dybdahl
Jul 22 '05 #3
>
As John mentions the first is a construction and the second an assignment.
Some classes will do the same in those cases. Others will do some more
initialization in the construction case. A few might do more work in the
assignment case.
Yes, I should have said the OP is comparing the cost of repeated copy
construction and destruction, with the cost of repeated assignment. It's
unlikely that assignment will be less efficient. But does return value
optimization play a role here? It seems to me that the compiler might be
able to do away with a temporary in the copy construction case. If so that
would swing things back in favour of copy construction.
I would prefer the construction case because of clarity caused by the
limited scope, unless I know for sure that the construction of the object is much more expensive than an assignment.


Absolutely, in general clarity of code is the most important efficiency
saving of all.

john
Jul 22 '05 #4
Robert Sturzenegger posted:
// Code sequence A
for (int i = 0; i < 10; ++i) {
int k = something();
// some more code which uses k
}

// Code sequence B
int k;
for (int i = 0; i < 10; ++i) {
k = something();
// some more code which uses k
}

Are the two sequences exactly the same in terms of performance, or has
the repeated instanciation of k in sequence A a certain cost compared
with the single one instantiation in sequence B?
What about if k were of a class type?
Thanks, Robert


I can guarantee that if one of them was faster, it would be B.

-JKop
Jul 22 '05 #5
"Robert Sturzenegger" <yo************ **@ziksuhy.ch> wrote in message news:<40******* *************** *@news.sunrise. ch>...
// Code sequence A
for (int i = 0; i < 10; ++i) {
int k = something();
// some more code which uses k
}

// Code sequence B
int k;
for (int i = 0; i < 10; ++i) {
k = something();
// some more code which uses k
}

Are the two sequences exactly the same in terms of performance, or has the
repeated instanciation of k in sequence A a certain cost compared with the
single one instantiation in sequence B?
With current compilers, exactly the same. In both cases compilers simply
reserve sizeof(int) bytes on the stack. This happens at compile time.
What about if k were of a class type?


In this case, it's unpredicatble. The first case has 10 ctor calls and
10 dtor calls. The second case has one ctor call, one dtor, and 10
assignments. The naive assumption would be that the first is more
expensive, but exceptio-safe assignments are usually implemented as
{ create temporary, swap contents, destroy temporary } which means
it includes both a ctor and dtor call. Then the second case is
more expensive.

Other cases may be even more complex. E.g. if k has type std::string,
the relative performance depends critically on the length of the
10 strings returned by something().

Regards,
Michiel Salters
Jul 22 '05 #6
JKop <NU**@NULL.NULL > wrote in message news:<8b******* **********@news .indigo.ie>...

[ ... ]
I can guarantee that if one of them was faster, it would be B.


It's sad that somebody like you seems to feel obliged to spend
inordinate amounts of time dreaming up wrong answers to give to even
ridiculously simple quesitons.

Fortunately, there is one good point: if you weren't dreaming up wrong
answers to give here, you'd probably be using one of your stolen
compilers to write code. Based on what you post here, anything that
prevents you from writing code HAS to be a good thing, even if it
means that beginners have to start out with a trial by fire (so to
speak) and quickly learn whose answers to ignore at nearly any cost.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '05 #7

Michiel Salters wrote:
Are the two sequences exactly the same in terms of performance, or has the
repeated instanciation of k in sequence A a certain cost compared with the
single one instantiation in sequence B?

With current compilers, exactly the same. In both cases compilers simply
reserve sizeof(int) bytes on the stack. This happens at compile time.


that makes no sense. stack allocations cannot happen at compile time.
think about it.

conceptually, sequence A would allocate stack space on each iteration
and clean it up at the end of the loop, where B would allocate the space
before the loop. i doubt that's what actually happens though, most
likely the compiler would adjust the stack before the loop. of course,
that's implementation dependent (hell, the compiler might even optimize
k away into a register in both sequences), but if it is the case, then
there should be no difference between the two.

mark

Jul 22 '05 #8
Jerry Coffin posted:
JKop <NU**@NULL.NULL > wrote in message
news:<8b******* **********@news .indigo.ie>...

[ ... ]
I can guarantee that if one of them was faster, it would be B.
It's sad that somebody like you seems to feel obliged to spend
inordinate amounts of time dreaming up wrong answers to give to even
ridiculously simple quesitons.


Then take some anti-depressants and get over it.
Fortunately, there is one good point: if you weren't dreaming up wrong
answers to give here, you'd probably be using one of your stolen
compilers to write code.
I'll be doing that anyway.
Based on what you post here, anything that prevents you from writing
code HAS to be a good thing, even if it means that beginners have to
start out with a trial by fire (so to speak) and quickly learn whose
answers to ignore at nearly any cost.


It's sad that somebody like you seems to feel obliged to spend inordinate
amounts of time responding to people you don't like.
-JKop

Jul 22 '05 #9

"JKop" <NU**@NULL.NULL > wrote in message
news:8b******** *********@news. indigo.ie...
Robert Sturzenegger posted:
// Code sequence A
for (int i = 0; i < 10; ++i) {
int k = something();
// some more code which uses k
}

// Code sequence B
int k;
for (int i = 0; i < 10; ++i) {
k = something();
// some more code which uses k
}

Are the two sequences exactly the same in terms of performance, or has
the repeated instanciation of k in sequence A a certain cost compared
with the single one instantiation in sequence B?
What about if k were of a class type?
Thanks, Robert


I can guarantee that if one of them was faster, it would be B.


How can you guarantee that? (And do I get my money back if you're wrong?
:-))

I'll make a guess that maybe you're talking about the integer case only. In
which, case, there's *probably* no difference in any modern compiler.

If you're including the object case as well, I'd say that guarantee ain't
worth the paper it ain't written on. (So to speak. :-)) As mentioned
elsewhere in this conversation, in the object case, B *might* actually be
*slower*, due to temporaries being constructed/destructed in addition to the
assignment.

In any case, it's not something that the standard defines, but rather is
implementation dependent.

-Howard


Jul 22 '05 #10

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

Similar topics

3
1225
by: thechaosengine | last post by:
Hi all, I get the following problem crop up every once in a while. I'm wondering if anyone can tell me how to avoid it because its driving me absolutely insane! I have a Project class that contains a User property amongst lots of other properties. In the Project class's constructor I initialise all the class's parameter *apart from* the User property. The magic is that at any point after calling
7
1686
by: johny smith | last post by:
Based on my experience there is two ways to instantiate an object. Method 1: Car* car1 = new Car();
18
5749
by: Erik Arner | last post by:
Hi, I really need some help here. After upgrading to g++ 3.4 I have run into all sorts of troubles that I'm sure depends on my lack of proper understanding of C++. I would now like to get it right once and for all, if possible. Most severe is the problem illustrated by the code below. It's based on the "pluggable factory pattern" described in http://www.adtmag.com/joop/crarticle.asp?ID=1520
12
2612
by: mlimber | last post by:
This is a repost (with slight modifications) from comp.lang.c++.moderated in an effort to get some response. I am using Loki's Factory as presented in _Modern C++ Design_ for message passing in an embedded environment with multiple processors. I created a policy for classes, which, I had hoped, would automatically register the class with the appropriate factory: // In some header file... #include <cassert>
3
2006
by: Anders Borum | last post by:
Hello! When declaring variables without immediately assigning a value, the CLR (please correct here) assigns a default value according to the (reference) type of the variable (e.g. string = null, int = 0 etc.). I always assign default values to my variables, but am unsure whether this degrades the performance of the instantiation of my classes. Are the following two classes as fast to instantiate?
13
1695
by: Jake Barnes | last post by:
I saw this sentence: "The last stage of variable instantiation is to create named properties of the Variable object that correspond with all the local variables declared within the function." here: http://jibbering.com/faq/faq_notes/closures.html
7
2448
by: John A Grandy | last post by:
I'm trying to get a decent idea of the relative performance of three types of implementations of data-access classes in ASP.NET 2.0. I believe this boils down to a more basic question regarding the cost of object instantiation in .NET 2.0. It becomes especially relevant to web-app data-access classes due to the vast variety of db queries page requests may require. Caching is not appropriate for most of these datasets, and so many...
2
3672
by: Florian Loitsch | last post by:
hi, What should be the output of the following code-snippet? === var x = "global"; function f() { var x = 0; eval("function x() { return false; }"); delete x; alert(x); }
9
2991
by: C#_Help_needed | last post by:
I need help with the following question. THANKS :) Write a program in c# that takes in a directory as a command line parameter, and returns the longest repeated phrase in ALL text files in that directory. Assume that all contents of all the files may be held in memory at the same time. Do not use unsafe code blocks and/ or pointers.
0
8399
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8732
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
8504
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
5632
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
4159
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
4318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2732
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
1959
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1622
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.