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

I'm trying to make a crossplatform simple webserver. In this server, I'm cacheing results to ease IO difficulties. I also want to provide a mechanism to limit the total memory used by the cache. I'd like to determine the amount of memory used by a variable (sometimes a complex object like an HTTP::Response) so that I can clear out the cache of either the least recently used or most memory intensive objects.

My question is: Is there a way to determine the size of a nonstandard object?

I could use an instance of the object's ->as_string method and get the length of that, but I'd prefer to have its actual size (not just the approximation from the size of its output).

  • Comment on How do I determine the amount of memory used by a variable?

Replies are listed 'Best First'.
Re: How do I determine the amount of memory used by a variable?
by hossman (Prior) on Dec 16, 2001 at 06:36 UTC
    That's not an easy question to answer when dealing with complex objects, because they can contain refrences to other objects (which might be shared between two or more obejcts you cache).

    The only way to get the info you really want, is to know how you are caching it -- if you are just storing it in memory, then the garbage collector is going to make sure that your object, and any other object it refrences stays arround. So what you need to do a complete traversal of all refrences in your object. If you are using something like Data::Dumper, or Storable, then it depends on how you use those libraries -- either way the safest way to know exactly how big it is, is to cache it to a file, and then check the file size.

Re: How do I determine the amount of memory used by a variable?
by Juerd (Abbot) on Dec 16, 2001 at 15:28 UTC
    It's not even possible to determine how much memory a variable really uses.
    When you have $a = 1, 1 is being saved. After using $a .= '', a string is added, but its numeric value is not forgotten.