Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Declaration of variable inside loop 1

Status
Not open for further replies.

Zoom1234

Programmer
Oct 30, 2003
116
BE
HI,
I want to know what impact (on memory etc) it does to declare variable inside loop instead of before loop.
Case
Code:
foreach (@testarr) {
 my $test = $_ ;
 # some code here
}
instead of
Code:
my $test ;
foreach (@testarr) {
 $test = $_ ;
 # some code here
}

 
With the first one, the variable is destroyed once the loop exits, so it doesn't continue hogging memory after the loop finishes. With the second, it persists and has the value of the last element of @testarr.
 
So which one is beter in terms of performance.
In first code, the variable gets declared for every iteration of loop. Does it cost performance overhead?
 
If we are focusing purely on performance, the second one would probably be slightly better. But this isn't the only criterion - the first is cleaner, more maintainable, and doesn't pollute your namespace with what amount to global variables. Add this to the fact that computing power doubles every 18 months (Moore's Law) for the same money, then unless you are really pushing the envelope of performance on your available hardware, I'd go with the first option.

Don't try to second-guess performance problems in advance - design it the 'right' way first and see how it performs. If you then discover you have a performance issue, find out exactly what's causing it (in many cases, it will be something out of left field and not what you'd expect), and change the design to accomodate it.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
instead of:

Code:
foreach (@testarr) {
 my $test = $_ ;
 # some code here
}

this is a more conventional way of writing the same code:

Code:
foreach my $test (@testarr) {
 # some code here
}
 
KevinADC,
I gave a wrong example code
I meant
Code:
foreach (@testarr) {
 my $test = "ABCD" ;
 # some code here
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top