in reply to Re: Two Questions on "my"
in thread Two Questions on "my"

> If you are worried about the memory that's being consumed by 2 scalars
>you should probably be coding in assembly.

What I'm actually worrying about is the TIME necessary to create the memory space versus the time it takes to simply assign a new value into existing memory space.

That whole "this will take a few seconds" from the next response? I'm wondering if that time could be cut down by reusing the memory space.

Some testing has shown me that it's about 1.5x as much time to do method 2 than method 1.

Charles Thomas
Madison, WI

Replies are listed 'Best First'.
Re: Re: Re: Two Questions on "my"
by hv (Prior) on May 22, 2004 at 18:48 UTC

    In general, when you have questions like this the real answer is to try it. The Benchmark module is your friend:

    use Benchmark qw/ cmpthese /; cmpthese(-5, { outside => q{ my $scalar; for (1..10_000) { $scalar = 1; } }, inside => q{ for (1..10_000) { my $scalar = 1; } }, });
    gives me:
    Rate inside outside inside 261/s -- -15% outside 307/s 18% --

    I'm not sure why the 'outside' version is faster, and it intrigues me - but if all you care about is which is faster, you don't need to know.

    Be careful about reading the percentages without noticing the rate though - since the assignment is happening 10,000 times for each iteration, we're talking about a 15% difference in speed for an operation that takes about a third of a microsecond. That is, you need to perform such an assignment about 18 million times before you can save 1 second by declaring the variable outside the loop. In most cases the clarity achieved by declaring the variable at the innermost scope far outweighs such microscopic savings.

    Hugo