Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

'my' and 'state' declaration inside a loop

by nemesisgus (Acolyte)
on Aug 05, 2012 at 01:26 UTC ( #985472=perlquestion: print w/ replies, xml ) Need Help??
nemesisgus has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

After reading this old but interesting thread: About "state" variables in Perl 5.10, it came to my mind if there is any difference in performance between this:

my $n; for (1..10000000) { $n = $_**2; }

and this:

for (1..10000000) { state $n = $_**2; }

given that, afaik, if we rewrite the second example using 'my', it does have an extra cost at runtime, since it is run once each time execution passes the 'my' declaration:

for (1..10000000) { my $n = $_**2; }

Is this "extra" time cost also present in the case of declaring the variable with 'state' although the variable is not reinitialized each time?

Thanks and sorry for the silly question.

PS: I know the second example generates a different output, but I'm mostly interested in the performance effect.

Comment on 'my' and 'state' declaration inside a loop
Select or Download Code
Replies are listed 'Best First'.
Re: 'my' and 'state' declaration inside a loop
by davido (Archbishop) on Aug 05, 2012 at 02:38 UTC

    It's really too silly of a concept to warrant the time needed to test it. The three constructs do different things entirely. If there's some situation where you have to care whether it's faster to declare a lexical inside a loop or outside, or whether state consumes more cycles than my, you should probably code that algorithm using Inline::C. ...and that still doesn't address the issue that these three snippets each do different things.

    But if you're really interested, Benchmark. It's a snipe hunt though.


Re: 'my' and 'state' declaration inside a loop
by 2teez (Priest) on Aug 05, 2012 at 03:08 UTC

    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:

    • perldoc -f my
    • perldoc -f state

      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
Re: 'my' and 'state' declaration inside a loop
by Marshall (Prior) on Aug 05, 2012 at 17:14 UTC
    my $n; for (1..10000000) { $n = $_**2; } versus: my $n; for (1..10000000) { state $n = $_**2; }
    In this sense, this is actually nonsense.

    See Perl State.

    Perl "state" is a way implement what would be called a "static" variable in 'C'. This is a way to initialize "a 'do it once' variable'" - often in a recursive subroutine.

    I have not seen anything like this in a for() loop. There is no reason.

    Update: Here is an example:

    #!/usr/bin/perl -w use strict; use 5.10.0; foreach (1..5) { print nextNum(),"\n"; } sub nextNum { state $num =10; return $num++; } __END__ Prints: 10 11 12 13 14

      Ok, my fist post didn't have good examples to show what I was pointing out.

      Consider a case like this where the three snippets produce the same output:

      Traditional my way:

      my $n; for (1..5) { $n++; say $n } __END__ Prints: 1 2 3 4 5

      New state way:

      for (1..5) { state $n++; say $n } __END__ Prints: 1 2 3 4 5

      I just was wondering if the fact of declaring the variable inside the loop has an extra cost compared to declaring the variable first out of the loop. But it seems like there is no difference in time cost as far as I could test anyway.

        Well, the "traditional" way is put the "my" variable in the scope of the loop.
        #!/usr/bin/perl -w use strict; use 5.10.0; ## my $n; for (1..5) { $n++; say $n } ## wrong foreach my $n (1..5) { say $n;} __END__ 1 2 3 4 5
        Maybe my previous example was not the best. But basically if you have something to initialize before a for loop starts iterating, do it in the for loop! "state" is actually a rather rare thing. You could code Perl for a year or two between using it.
Re: 'my' and 'state' declaration inside a loop
by Anonymous Monk on Aug 05, 2012 at 16:20 UTC
    In any case I would not choose one vs. the other on the notion that it is "more" or "less" "efficient." Use the cleanest construct that makes the most sense to you to get the job done, and be done with it. It's truly an extraordinary edge-case when a profiler demonstrates a difference in such things that actually makes a difference.
      Thanks for your comment, I agree. Clarity is preferred over a slight gain in performance if the same task can be achieved in different ways.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://985472]
Approved by chacham
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2015-11-25 22:24 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (692 votes), past polls