in reply to Two Questions on "my"

Answer1

In both cases you reuse the same memory space. lexicals only use more memory in case of a recursive subroutine call, but then, you usually want them too.

Anyway, generally you want variables to have the smallest possible scope, so I'd go for option two.

Answer2

I really don't know what you are talking about, and I don't get the example code either.

You cannot "return an array", you always return a list (when the sub is called in list context) or a single scalar value (otherwise). If you want to return a long list efficiently, return an array reference, and never mind copying the reference. If you are worried about the memory that's being consumed by 2 scalars, you should probably be coding in assembly.

Replies are listed 'Best First'.
Re: Re: Two Questions on "my"
by C_T (Scribe) on May 22, 2004 at 16:10 UTC
    > 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

      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