in reply to returning ref to static var vs. copying

Is there any significant differences between the two in terms of performance or memory usage?

If @list is big, yes. The latter makes a copy, which takes time, and uses about twice the amount of memory, half of which is available for reuse since @list goes out of scope.

Are there any potentially adverse consequences of holding on to references to static variables?
The closest thing Perl has to static variable are "state" variables (new in 5.10). Your codes doesn't have any.

Returning references may have the danger that something else is also holding some reference to it. And he who has the reference has the power to modify it. If there's nothing else holding a reference, there's little danger.

  • Comment on Re: returning ref to static var vs. copying

Replies are listed 'Best First'.
Re^2: returning ref to static var vs. copying
by perl5ever (Pilgrim) on Jun 10, 2009 at 15:00 UTC
    I guess I meant to say lexical instead of static.
    If @list is big, yes. ...
    One thing I was wondering was if perl can optimize this case and not perform the copy.
      Determining whether something is big is easy. But returning a reference is something else that returning a copy. One could determine in a limited amount of cases whether returning a reference instead of a copy isn't hurtful (but not in general, as that will involve solving the halting problem), but
      1. Determining something like that takes time. Which means that each such case slows down. Even if in the end the conclusion is that the copy needs to be done after all.
      2. The gain for the programmer would be minimal. It's not that [@list] is shorter to write than \@list.
      3. Noone has written such a patch.
      Given 1) and 2), even if someone did 3) I wouldn't bet on it it gets accepted.

        ... and 4. Sometimes, you just WANT to get/return a reference to a fresh copy, e.g. because you don't want the caller to damage the original array.

        Alexander

        --
        Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)