bsb has asked for the wisdom of the Perl Monks concerning the following question:

From the Class::Accessor docs:

Also, the accessors are implemented as closures which should cost a bit less memory than most other solutions which generate a new method for each accessor.

Why should closures be cheaper in this situation?

Replies are listed 'Best First'.
Re: Why do closures save memory?
by sauoq (Abbot) on Jul 07, 2003 at 11:30 UTC
    Why should closures be cheaper in this situation?

    Its the difference between having one function and many. The closures can all use the same compiled code internally; only a copy of the lexical environment needs to be kept. Generating accessors by eval'ing them into existence, the strategy used by Class::Struct as revealed by PodMaster, results in newly compiled code for each one.

    -sauoq
    "My two cents aren't worth a dime.";
    
      Thanks. I thought that might be the reason but I didn't want to rig the ballot.

      I only started thinking about it after reading that note in Class::Accessor. Prior to that I'd naively assumed you got a whole new function even with closures.

      Brad

Re: Why do closures save memory?
by PodMaster (Abbot) on Jul 07, 2003 at 07:30 UTC
    A quick investigation to see how Class::Struct generates its accessors reveals an eval. eval is expensive (string evail that is, the kind used in Class::Struct, indicated by ###########################<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< in readmore). update: made somenotes on top, they're in bold. Also added reamore. Thanks grantm, that is an important distinction.

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

      eval is expensive

      Just to pick a nit, I'm sure what you meant to say was "eval of a string is expensive".

      The cost of wrapping eval around a block is less than the cost of a subroutine call. Since eval of a block is the standard way to catch exceptions I think it's important we don't leave people with the impression that catching exceptions is expensive.