473,385 Members | 1,642 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.

nested variables in loops - inefficient?

Using local declarations within a block often makes code more readable, but
is it less efficient? eg...

void P() {
while (...) {
int i = ...;
bool b = ...;
....
}
}

At first sight this looks inefficient, because i and b are being allocated
each time around the loop. But I wonder if that is really the case. I have
heard that when procedure P is placed on the stack, that *all* variables
within P, including those within a nested scope, are also allocated. ie. in
the above example, i and b would be allocated only once, at the start of the
procedure. However, I am not sure whether this is the true.

What if the the variable is nested within a conditional - is it still always
allocated at the start? eg...

while (...) {
if (...) {
int i = ...;
bool b = ...;
....
}
}
Any experts here who can ease my mind about the possible ineffiency of
nested variables?

A bit of background - I'm writing a real time application, with several
complex loops processing data which is being received at a high rate, so I
keep coming across this dilemna.

TIA,

Javaman
Nov 17 '05 #1
9 2459
No matter *where* the variables are located in the method: they all are
allocated only *once*.
But if you assign a value to them, e.g. int i=0; the assignment takes place
everytime this line of code is executed.

"Javaman59" <Ja*******@discussions.microsoft.com> schrieb im Newsbeitrag
news:4F**********************************@microsof t.com...
Using local declarations within a block often makes code more readable,
but
is it less efficient? eg...

void P() {
while (...) {
int i = ...;
bool b = ...;
....
}
}

At first sight this looks inefficient, because i and b are being allocated
each time around the loop. But I wonder if that is really the case. I have
heard that when procedure P is placed on the stack, that *all* variables
within P, including those within a nested scope, are also allocated. ie.
in
the above example, i and b would be allocated only once, at the start of
the
procedure. However, I am not sure whether this is the true.

What if the the variable is nested within a conditional - is it still
always
allocated at the start? eg...

while (...) {
if (...) {
int i = ...;
bool b = ...;
....
}
}
Any experts here who can ease my mind about the possible ineffiency of
nested variables?

A bit of background - I'm writing a real time application, with several
complex loops processing data which is being received at a high rate, so I
keep coming across this dilemna.

TIA,

Javaman

Nov 17 '05 #2
There answer to your efficiency question is that it depends. In a release
build where the compiler optimizes your code it will defintely move the int
outside the scope of the loop. For value types it really doesn't matter
because they'll be on the stack anyway. For reference types however each
time through the loop would cause the object to be release and therefore
potentially GC'ed while a new one is created. Thus I wouldn't do this sort
of thing for strings.

The more important question however is the initialization of that var.
Given your code do you expect the local to be inited each time through the
loop? If so then the assignment must happen during each iteration even if
the object creation happens only once.

By moving the var outside the loop you are also impacting the visibility
scope of the var. You won't be able to declare another "i" in this function
if it is moved outside the loop. However if it remains in the loop then you
can reuse "i" in other loops.

Compilers are really good at optimizing simple cases like this one. The
compiler will move any code that is loop invariant outside the scope of the
loop. Therefore I wouldn't worry about the general case you mentioned unless
you're dealing with reference types.

Personally I always put local vars outside the loop but this is really a
holdover from my days of writing real-time compilers in C++. It's not as
readable but it feels "faster" to me.

Michael Taylor - 9/19/05

"Javaman59" wrote:
Using local declarations within a block often makes code more readable, but
is it less efficient? eg...

void P() {
while (...) {
int i = ...;
bool b = ...;
....
}
}

At first sight this looks inefficient, because i and b are being allocated
each time around the loop. But I wonder if that is really the case. I have
heard that when procedure P is placed on the stack, that *all* variables
within P, including those within a nested scope, are also allocated. ie. in
the above example, i and b would be allocated only once, at the start of the
procedure. However, I am not sure whether this is the true.

What if the the variable is nested within a conditional - is it still always
allocated at the start? eg...

while (...) {
if (...) {
int i = ...;
bool b = ...;
....
}
}
Any experts here who can ease my mind about the possible ineffiency of
nested variables?

A bit of background - I'm writing a real time application, with several
complex loops processing data which is being received at a high rate, so I
keep coming across this dilemna.

TIA,

Javaman

Nov 17 '05 #3
Javaman59 <Ja*******@discussions.microsoft.com> wrote:
Using local declarations within a block often makes code more readable, but
is it less efficient? eg...

void P() {
while (...) {
int i = ...;
bool b = ...;
....
}
}


In the following, P() And Q() compile down to the exact same IL for me (and
optimization is *off*). You can try it yourself with ILDASM.

using System;

class Test
{
static void Main() {
P();
Q();
}

static void P() {
while (true) {
int i = Console.Read();
bool b = i == 5;
Console.WriteLine(i);
Console.WriteLine(b);
}
}

static void Q() {
int i;
bool b;
while (true) {
i = Console.Read();
b = i == 5;
Console.WriteLine(i);
Console.WriteLine(b);
}
}
}
Nov 17 '05 #4
Thanks! Your reply came in while I was writing my own response to the other
two.

Thanks for writing that bit of code. I think that settles it. Smart to use "
int i = Console.Read(); bool b = i == 5;" to ensure that the compiler
doesn't optimise the expressions!

Regards,

Javaman.
"Cool Guy" wrote:
Javaman59 <Ja*******@discussions.microsoft.com> wrote:
Using local declarations within a block often makes code more readable, but
is it less efficient? eg...

void P() {
while (...) {
int i = ...;
bool b = ...;
....
}
}


In the following, P() And Q() compile down to the exact same IL for me (and
optimization is *off*). You can try it yourself with ILDASM.

using System;

class Test
{
static void Main() {
P();
Q();
}

static void P() {
while (true) {
int i = Console.Read();
bool b = i == 5;
Console.WriteLine(i);
Console.WriteLine(b);
}
}

static void Q() {
int i;
bool b;
while (true) {
i = Console.Read();
b = i == 5;
Console.WriteLine(i);
Console.WriteLine(b);
}
}
}

Nov 17 '05 #5
Thanks, very much.
while (...) {
int i = ...;
bool b = ...;
....
}
Both of you pointed out that I needn't be concerned about the allocation of
the variables - that will happen once only, no matter where they are in the
method. The right of the assignment statement will be executed each time
round the loop, obviously, and in my case it needs to be, as the value of the
expression changes each time.

So, I don't really need to declare the variables outside the loop for the
sake of efficiency (it makes no difference), but, still, my instincts are the
same as Michael's...
Personally I always put local vars outside the loop but this is really a
holdover from my days of writing real-time compilers in C++. It's not as
readable but it feels "faster" to me.


Somehow, the declaration outside the loop feels right to me. Perhaps it is
actually clearer, as it shows what is changing with each iteration.

Thanks again,

Javaman
"Javaman59" wrote:
Using local declarations within a block often makes code more readable, but
is it less efficient? eg...

void P() {
while (...) {
int i = ...;
bool b = ...;
....
}
}

At first sight this looks inefficient, because i and b are being allocated
each time around the loop. But I wonder if that is really the case. I have
heard that when procedure P is placed on the stack, that *all* variables
within P, including those within a nested scope, are also allocated. ie. in
the above example, i and b would be allocated only once, at the start of the
procedure. However, I am not sure whether this is the true.

What if the the variable is nested within a conditional - is it still always
allocated at the start? eg...

while (...) {
if (...) {
int i = ...;
bool b = ...;
....
}
}
Any experts here who can ease my mind about the possible ineffiency of
nested variables?

A bit of background - I'm writing a real time application, with several
complex loops processing data which is being received at a high rate, so I
keep coming across this dilemna.

TIA,

Javaman

Nov 17 '05 #6
Hi,

"TaylorMichaelL" <Ta************@discussions.microsoft.com> wrote in message
news:AC**********************************@microsof t.com...
There answer to your efficiency question is that it depends. In a release
build where the compiler optimizes your code it will defintely move the
int
outside the scope of the loop. For value types it really doesn't matter
because they'll be on the stack anyway. For reference types however each
time through the loop would cause the object to be release and therefore
potentially GC'ed while a new one is created. Thus I wouldn't do this
sort
of thing for strings.
Well usually you use that construction to hold a reference to an object
already created and that is currently being referenced by another mean, in
which case you do not have that problem.
Neither you have more choises if what is created is the return of a method
that create a new instance. instance that you should need to use in the
loop.
The more important question however is the initialization of that var.
Given your code do you expect the local to be inited each time through the
loop? If so then the assignment must happen during each iteration even if
the object creation happens only once.
With values types it shoudl not matter, I'm not very familiar with the IL
code, but I bet you that the space in the stack is reserved only once. The
assignment will happen in each iteration, and that is why you have it inside
the loop in the first place. Ideally it should get a new value in each
iteration, or at least a value based in the list being iterated on.

Personally I always put local vars outside the loop but this is really a
holdover from my days of writing real-time compilers in C++. It's not as
readable but it feels "faster" to me.


You should declare them outside only in the case that you need an especific
initial value that is not derived from the list being iterated, otherwise
IMO they should be put inside the loop
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Nov 17 '05 #7
cody wrote:
No matter *where* the variables are located in the method: they all are
allocated only *once*.
But if you assign a value to them, e.g. int i=0; the assignment takes place
everytime this line of code is executed.

Surely they are allocated off the top of the stack, so will be allocated
on each loop entry, but this will only be whatever the .NET equivalent
of add sp,4 ; mov [sp-4],0 is ?
Nov 17 '05 #8
"Paul Robson" <au******@autismuk.muralichucks.freeserve.co.uk> schrieb im
Newsbeitrag news:dg**********@news7.svr.pol.co.uk...
cody wrote:
No matter *where* the variables are located in the method: they all are
allocated only *once*.
But if you assign a value to them, e.g. int i=0; the assignment takes
place everytime this line of code is executed.

Surely they are allocated off the top of the stack, so will be allocated
on each loop entry, but this will only be whatever the .NET equivalent of
add sp,4 ; mov [sp-4],0 is ?


I think the allocation itself (add sp,4) will take place only once for each
call of that method.
But the assignment (mov [sp-4],0) will take place in every iteration of the
loop.
Nov 17 '05 #9
Javaman59 <Ja*******@discussions.microsoft.com> writes:
Using local declarations within a block often makes code more readable, but
is it less efficient? eg...
[...]
Any experts here who can ease my mind about the possible ineffiency of
nested variables?


As shown by others, it makes no difference in the IL whether you put
the declarations inside or outside.

So put them where they logically belong in your case: inside the
loop.

Once you use an anonymous method inside the loop it makes a great
(semantic, not just efficiency) difference whether you put it inside
or not.

Peter
--
Department of Natural Sciences http://www.dina.kvl.dk/~sestoft/
Royal Veterinary and Agricultural University * Tel +45 3528 2334
Thorvaldsensvej 40, DK-1871 Frederiksberg C, Denmark * Fax +45 3528 2350
Nov 17 '05 #10

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

Similar topics

25
by: chad | last post by:
I am writing a program to do some reliability calculations that require several nested for-loops. However, I believe that as the models become more complex, the number of required for-loops will...
46
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are...
2
by: neildunn | last post by:
Hey guys: >>> >>> def a(): .... print .... >>> a() Traceback (most recent call last): File "<stdin>", line 1, in ?
77
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop....
9
by: Gregory Petrosyan | last post by:
I often make helper functions nested, like this: def f(): def helper(): ... ... is it a good practice or not? What about performance of such constructs?
5
by: =?Utf-8?B?QUEyZTcyRQ==?= | last post by:
Could someone give me a simple example of nested scope in C#, please? I've searched Google for this but have not come up with anything that makes it clear. I am looking at the ECMA guide and...
9
by: notahipee | last post by:
Would someone be able to tell me why this isn't working. The nested for loops seem correctly coded to me. I would appreciate any input. #include <iostream.h> #include <math.h> int main () {...
4
by: Sheldon | last post by:
Hi, I have a unique case where I need an array of structs that grows and within this array is another struct that grows in some cases. I'm having trouble allocating memory. Since I have never...
8
by: Nathan Sokalski | last post by:
I have several nested For loops, as follows: For a As Integer = 0 To 255 For b As Integer = 0 To 255 For c As Integer = 0 To 255 If <Boolean ExpressionThen <My CodeElse Exit For Next If Not...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.