in reply to 'my' and 'state' declaration inside a loop

You will really want to Benchmark these to find out. But you need bear in mind just as mentioned perviously, that these does different things in different concept. They might be similar in their usage though. You might also want to check these:

  • Comment on Re: 'my' and 'state' declaration inside a loop

Replies are listed 'Best First'.
Re: 'my' and 'state' declaration inside a loop
by nemesisgus (Acolyte) on Aug 05, 2012 at 16:22 UTC

    Thank you both for your wisdom.

    I read the my and state docs before asking but I couldn't find an answer.

    I understand that state was introduced as an improvement to my and that they have different purposes although they are overlapping in some cases and can be used to reach the same effect.

    My question was basically conceptual.

    Anyway, just if somebody is interested, it seems that there is, of course, a difference:

    my $n; for (1..100000000) { $n=0 } real 0m9.395s user 0m9.397s sys 0m0.000s _________________________________ for (1..100000000) { my $n=0 } real 0m12.773s user 0m12.765s sys 0m0.004s _________________________________ for (1..100000000) { state $n=0 } real 0m7.282s user 0m7.244s sys 0m0.008s

      state is not an 'improvement' of my. It is an improvement of Perl to provide a small feature that was missing - scoped static variables. The common part between my and state variables is that they can't be accessed by name outside their lexical scope. The prime difference between them is that my variables get a fresh chunk of memory each time their lexical scope is entered whereas static variables are assigned a chunk of memory at program start time and retain it until execution terminates.

      True laziness is hard work