Does garbage collector in Ruby take into account the size as well as the amount of objects? For optimization, I’m considering of replacing Class instances with either Structs or plain Hashes. I would like to understand which given classes will have have the greatest impact on garbage collection.
Does garbage collector in Ruby take into account the size as well as the
Share
The guy who said that you should benchmark it is right — GC is a complex issue and it’s hard to give a 100% correct answer.
Also, it depends on the implementation being used. In JRuby, it’s the JVM doing the work. In MRI, it’s a mark-and-sweep GC.
On the case of MRI, it works more or less like this: each time that the Ruby interpreter needs more memory, it runs the GC to try and free it. If there isn’t enough memory, it’ll allocate more. And the GC decides that an object is ok to be freed (“mark” it) when there aren’t references to it.
The only advice I can give you is to avoid using lots of objects that can’t be garbage collected. For example, if you’re building an array of strings (their size isn’t important), you should see performance degradation much more rapidly than if you created a big string concatenating each of the smaller ones.
This is because in the latter the GC can destroy the small strings after they’re used, while in the former the array is always maintaining a reference to each one of them.
EDIT: Of course, this assumes that the cost of maintaining them in memory is bigger than the slowdown of dealing with the “big string”. In some cases, it’s better to have small strings and then concatenate they all — resulting in a single slow operation. Again, these are just examples without benchmarks, don’t take them very seriously.