From: "bramski@..." Date: 2008-06-19T03:13:49+09:00 Subject: Re: Can I find out the memory used by an object? > > > Typically you would rather be interested in a particular part of the > > > object graph that is reachable from an instance - and here it becomes > > > difficult, because any object can have any number of references and > > > can be referred to any number of times.  Where then do you count the > > > memory?  Or do you count it multiple times? etc. It sounds to me like you want to patch ruby's garbage collection. Albeit a bit of a dark art, this will probably get you the answer you want. You really want to know the answer to: If I free this object, how much memory will I gain? As a lot of the replies here imply, answering this question is not simple at all. Particularly if two of the objects in your cache happen to share one large object between them. In which case, freeing neither will gain you much memory. I believe you essentially wish to modify the GC's mark and sweep algorithm to do graph traversal of the object graph, and to intelligently sum the cumulative size of objects within the graph. However, the structure of the object reference graph is not nearly as structured as a file system, and the cascading effect of adding a complex object to a hashtable on the calculated sizes makes doing caching very difficult. Back to your original posting.. 1) Marshall dumping to determine these sizes. I think this will be faster than running a modified GC algorithm or object graph traversal to try and determine how much memory you'd earn if you freed a particular element. However, this in some cases won't answer your question correctly due to other people holding onto references to internal elements of the object you just marshalled. Though if you can guarantee that your objects aren't being referenced externally this will work well. 2) Figuring out your sizes via process size. I actually think this is your best option. Why not turn your system into a Drb engine? Unfortunately you'll be marshall dumping and loading the whole thing each time, but you'll at least get an accurate answer. However, what I'm curious about, is why do this uber-complex thing in the first place? You'd run into the problem of trying to figure out memory sizes and utilization in almost any language due to not understanding the thing you're actually caching. Caches are generally designed to store relatively well known things, not giant spaghetti monsters, that's how they gain their efficiency. I mean, imagine a system that caches filehandles, who knows what resources you're actually tying up by holding onto those filehandles?