473,698 Members | 2,025 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

very simple question

Hi everyone,

I just wanted to know if there is any difference in performance in
declarating the variables in the beginning of a function or within for
loops. For example:

double test()
{
double a,b,c;
for(int i=0; i<n; i++){
a = i*10;
b = a-i;
c += a*b;
}
return c;
}

or:

double test()
{
double c;

for(int i=0; i<n; i++){
double a = i*10;
double b = a-i;
c += a*b;
}
return c;
}

May 17 '07 #1
13 1536
aaragon wrote:
I just wanted to know if there is any difference in performance in
declarating the variables in the beginning of a function or within for
loops. [..]
There is no way to know before actually clocking both functions.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 17 '07 #2
aaragon wrote:
double test()
{
double c;

for(int i=0; i<n; i++){
double a = i*10;
double b = a-i;
c += a*b;
}
return c;
}
Google "premature optimization". Always write the version that's easiest for
programmers to understand. Your second version makes a and b's role clear.

And, at the level of variable placement, there is almost nothing you can do
better than the compiler would do it. The compiler will probably optimize a
and b almost away, and will only use an FPU register, no matter where you
declare them.

--
Phlip
http://flea.sourceforge.net/PiglegToo_1.html
May 17 '07 #3
"aaragon" <al************ **@gmail.comwro te in message
news:11******** **************@ l77g2000hsb.goo glegroups.com.. .
Hi everyone,

I just wanted to know if there is any difference in performance in
declarating the variables in the beginning of a function or within for
loops. For example:

double test()
{
double a,b,c;
for(int i=0; i<n; i++){
a = i*10;
b = a-i;
c += a*b;
}
return c;
}

or:

double test()
{
double c;

for(int i=0; i<n; i++){
double a = i*10;
double b = a-i;
c += a*b;
}
return c;
}
consider if n == 0. if n==0 for your second example the varibles would
never have to be allocated.

If they will always be allocated (n 0) then the difference is assignment
..vs. initialization. For simple types (double, float, etc...) it probably
doesn't make much difference. For classes, however, it can if they have
constructors that take time.

The general rule in C++ is delcare varaibles just before you use them. One
of the main reasons is so you know what the variable is declared. If a
function is large and you come across
a = 10;
what is a? Is it int? double? char? a class? You'd have to scroll up to
the top of the function to find out. However
double a = 10;
makes it easier to read/maintain the code IMO.
May 17 '07 #4
aaragon wrote:
Hi everyone,

I just wanted to know if there is any difference in performance in
declarating the variables in the beginning of a function or within for
loops. For example:

double test()
{
double a,b,c;
for(int i=0; i<n; i++){
a = i*10;
b = a-i;
c += a*b;
}
return c;
}

or:

double test()
{
double c;

for(int i=0; i<n; i++){
double a = i*10;
double b = a-i;
c += a*b;
}
return c;
}
Simple question, simple answer. No difference at all.

Let the compiler take care of optmization. In fact if you declare your
variables where they are used it is EASIER for the compiler to optimise
your code.

Concentrate on writing good clear code, computer time is cheap,
programmer time is expensive. Try to optimize the latter not the former.

john
May 17 '07 #5
John Harrison wrote:
Simple question, simple answer. No difference at all.

Let the compiler take care of optmization. In fact if you declare your
variables where they are used it is EASIER for the compiler to optimise
your code.

Concentrate on writing good clear code, computer time is cheap,
programmer time is expensive. Try to optimize the latter not the former.
I agree with you. A couple of notes, though:

1) from time to time there are optimizations that the compiler can't do
so easily. For example, if the variables are classes with a non-trivial
constructor, I don't think the compiler will try to understand if the
behaviour is the same calling the constructor just once or for each
step. Anyway, this kind of optimization has to be done once the program
is complete and working, testing the changes for the performances. At
the moment of writing, just put a bookmark in that piece of code.

2) Allocating an integer in the stack in most architecture is a matter
of subtracting the size of the integer from the stack pointer, and this
just if the compiler doesn't optimize the code. So, in the example
originally posted the difference would be really negligible anyway.

Regards,

Zeppe
May 17 '07 #6

aaragon a scris:
Hi everyone,

I just wanted to know if there is any difference in performance in
declarating the variables in the beginning of a function or within for
loops. For example:

double test()
{
double a,b,c;
for(int i=0; i<n; i++){
a = i*10;
b = a-i;
c += a*b;
}
return c;
}

or:

double test()
{
double c;

for(int i=0; i<n; i++){
double a = i*10;
double b = a-i;
c += a*b;
}
return c;
}
Hello,

C++ idioms tells that you should declare variables very close where
you need to use them. For simple types there is no big difference, but
when you use objects, declaring variables will call constructors which
can allocate memory and will slow down the application pretty much.
It all depends of what you need to do.

May 17 '07 #7
On May 17, 11:23 am, aaragon <alejandro.ara. ..@gmail.comwro te:
Hi everyone,

I just wanted to know if there is any difference in performance in
declarating the variables in the beginning of a function or within for
loops. For example:

double test()
{
double a,b,c;
for(int i=0; i<n; i++){
a = i*10;
b = a-i;
c += a*b;
}
return c;

}

or:

double test()
{
double c;

for(int i=0; i<n; i++){
double a = i*10;
double b = a-i;
c += a*b;
}
return c;

}
In this case, none whatsoever on all compilers I use - YMMV. However
if the objects created in the loop have a non-trivial constructor (or
a constructor that can't be optimized away to nothing), then it can be
quite expensive to have them constructed in the loop.

May 17 '07 #8
Gianni Mariani wrote:
:: On May 17, 11:23 am, aaragon <alejandro.ara. ..@gmail.comwro te:
::: Hi everyone,
:::
::: I just wanted to know if there is any difference in performance in
::: declarating the variables in the beginning of a function or
::: within for loops. For example:
:::
::: double test()
::: {
::: double a,b,c;
::: for(int i=0; i<n; i++){
::: a = i*10;
::: b = a-i;
::: c += a*b;
::: }
::: return c;
:::
::: }
:::
::: or:
:::
::: double test()
::: {
::: double c;
:::
::: for(int i=0; i<n; i++){
::: double a = i*10;
::: double b = a-i;
::: c += a*b;
::: }
::: return c;
:::
::: }
::
:: In this case, none whatsoever on all compilers I use - YMMV.
:: However if the objects created in the loop have a non-trivial
:: constructor (or a constructor that can't be optimized away to
:: nothing), then it can be quite expensive to have them constructed
:: in the loop.

On the other hand, if the constructor is expensive, so is possibly
also the assignment operator. In that case, we cannot generally tell
if it is cheaper to change the value of an object, or create one from
scratch with the right value.

The advice is to not bother until you notice that this actually is the
bottle neck in your program. It usually never is!

I would go for option 2, because I think it looks better. That makes
it easier for me to understand.
Bo Persson
May 17 '07 #9
On 17 Maj, 11:23, asterisc <Rares....@ni.c omwrote:
aaragon a scris:


Hi everyone,
I just wanted to know if there is any difference in performance in
declarating the variables in the beginning of a function or within for
loops. For example:
double test()
{
double a,b,c;
for(int i=0; i<n; i++){
a = i*10;
b = a-i;
c += a*b;
}
return c;
}
or:
double test()
{
double c;
for(int i=0; i<n; i++){
double a = i*10;
double b = a-i;
c += a*b;
}
return c;
}

Hello,

C++ idioms tells that you should declare variables very close where
you need to use them. For simple types there is no big difference, but
when you use objects, declaring variables will call constructors which
can allocate memory and will slow down the application pretty much.
It all depends of what you need to do.
Well... that constructor call does useful work - initialising the
object to a well-known state. For an object declared at an outer
scope, some amount of work would have to be done getting that same
initialisation. You'll often find that that other work results in
slower code than using the straight forward non-obscuring method of
declaring the variable where it belongs.

/Peter

May 17 '07 #10

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

Similar topics

11
4651
by: Frag | last post by:
Hi guys, I searched around without any clear answer. Tons of stuff, but nothing concrete. I am trying to call this Javascript function: function ButtonClicked() { alert("The button has been clicked."); }
4
1215
by: Geoff Cox | last post by:
Hello, No doubt this is simple but I cannot see how to do it ... I have a variable called situation_number with a series of values 1, 2, 3 etc. I would like to have a series of variables situation-1, situation-2 etc where the numbers 1 and 2 come from the situation_number variable.
3
1717
by: suzy | last post by:
Hello, I am trying to write a generic tool that accesses a SQL server and reads/updates/deletes/creates records. I want to reference this tool from my asp.net pages to talk to my db. by the way, i want the results of any read, update and create to be returned in xml. when reading data, i populate a dataset with data and then use the dataset.getxml method to return xml. is this a neat way of reading data? how does it compare to the...
29
1695
by: Knut Olsen-Solberg | last post by:
I try to change the text in a <p> using getElementById(). I wonder what properties exists, and which one to use here. (The following does not work.) Regards Knut ______________________ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <TITLE>JavaScript</TITLE>
7
1083
by: Badass Scotsman | last post by:
Hello, I have some "runat server" form boxes on the page, for example: <asp:textbox class="textbox" runat="server" type="text" name="Email" maxlength="200" id="Email" value="" /> How can I prepopulate this field from the QueryString? The following creates an error:
1
1278
by: Simon | last post by:
A very simple question that is very hard to google..(so please be so kind to answer it, if you have the answer.) How can I reach an iframe, located in another frame. Situation: frameset of three frames. Left frame (LFRAME) Right frame (RFRAME) Top frame (HFRAME) (and an iframe, called progressbar)
4
2097
by: psychofish25 | last post by:
I just have one simple question. How do I open a python script from the interactive window? Or do I have to go to File->Open?
5
1342
by: jackinoob | last post by:
Hi All, Apologies in advance, this question is very rudimentary, but I can't seem to get it right. I am running python within cygwin. I have a python script called test.py, and inside it a function defined simply as def square(x): return x*x print "hello world"
5
1757
by: Ibys | last post by:
Hi, i am just starting to learn javascript, so i am probably doing something very simple wrong. i have read a lot of articles on maths in java, but cant find anything simple enough for my problem. I am looking for how to get an IF statement to give me the correct output. I am trying to get it to give me a result for a weeks pay, taking that the code worked before i tried to add the IF statement, to make it that if HoursWorked >= 20, the rate of...
0
8668
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
9152
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
8855
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
7708
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...
0
5857
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
4358
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
4612
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2320
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1995
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.