Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: 'my' and 'state' declaration inside a loop

by nemesisgus (Acolyte)
on Aug 05, 2012 at 16:22 UTC ( #985548=note: print w/ replies, xml ) Need Help??


in reply to Re: 'my' and 'state' declaration inside a loop
in thread 'my' and 'state' declaration inside a loop

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


Comment on Re: 'my' and 'state' declaration inside a loop
Select or Download Code
Re^2: 'my' and 'state' declaration inside a loop
by GrandFather (Cardinal) on Aug 07, 2012 at 20:32 UTC

    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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://985548]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2014-07-13 04:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (245 votes), past polls