473,385 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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 1514
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.comwrote in message
news:11**********************@l77g2000hsb.googlegr oups.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.comwrote:
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.comwrote:
::: 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.comwrote:
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
"peter koch" writes:
>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.
That presumes you actually *want* that state. If some humongous tree is
already in RAM, or some equivalent, you don't necessarily want a replacement
tree. I am sure there are cases where your point is valid, but I think it
needed qualifiers.

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.

May 17 '07 #11
On May 17, 12:10 pm, "osmium" <r124c4u...@comcast.netwrote:
"peter koch" writes:
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.

That presumes you actually *want* that state. If some humongous tree is
already in RAM, or some equivalent, you don't necessarily want a replacement
tree. I am sure there are cases where your point is valid, but I think it
needed qualifiers.

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.
Thank you guys for your help. I'll finally go with the second option.

May 20 '07 #12
On May 17, 2:38 am, Gianni Mariani <gi3nos...@mariani.wswrote:
On May 17, 11:23 am, aaragon <alejandro.ara...@gmail.comwrote:
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.
But if constructing the object is expensive, then assigning an already-
constructed object a value is likely to be even more expensive (And
yes, that observation might sound counter-intuitive). But in fact it's
probably safe to say that most C++ programming books (include Meyers'
"Effective C++") advise their readers to prefer construction-
initialization over assignment. So, unless there is some specific
reason for doing otherwise, declaring the objects within the for loop,
will likely turn out to be the more efficient choice.

Greg
May 21 '07 #13
On Mon, 21 May 2007 03:24:15 -0700, Greg Herlihy wrote:
On May 17, 2:38 am, Gianni Mariani <gi3nos...@mariani.wswrote:
>On May 17, 11:23 am, aaragon <alejandro.ara...@gmail.comwrote:
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.

But if constructing the object is expensive, then assigning an already-
constructed object a value is likely to be even more expensive
I can think of one (common?) case where this is not likely to be so: when
construction involves expensive memory allocation and assignment does not
require that memory be re-allocated (eg. construction of a large vector
and assignment from a vector of the same or smaller size).
(And yes,
that observation might sound counter-intuitive). But in fact it's
probably safe to say that most C++ programming books (include Meyers'
"Effective C++") advise their readers to prefer construction-
initialization over assignment.
In general, yes...
So, unless there is some specific reason
for doing otherwise, declaring the objects within the for loop, will
likely turn out to be the more efficient choice.
Perhaps the situation I suggest above supplies one such "specific reason".

--
Lionel B
May 21 '07 #14

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

Similar topics

11
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...
4
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...
3
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...
29
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 ______________________ ...
7
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...
1
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...
4
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
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...
5
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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,...
0
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...

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.