Wednesday, March 5, 2014

Using GC vs. ObjectSpace for Counting Arrays, etc. Created in Ruby

One way to use ObjectSpace to diff the number of Ruby arrays created is:

def log_objectspace_object_count_delta(key)
  orig = ObjectSpace.count_objects[key]
  yield
  puts "#{ObjectSpace.count_objects[key] - orig} ObjectSpace objects created"
end

Which would let you specify the key, in this case :T_ARRAY, to find the delta in object count:

2.1.0p0 :006 > log_objectspace_object_count_delta :T_ARRAY do; nil; end
0 ObjectSpace objects created
 => nil 
2.1.0p0 :007 > log_objectspace_object_count_delta :T_ARRAY do; []; end
1 ObjectSpace objects created
 => nil 

GC has a nice little stat method that might also help, e.g.:

def log_gc_objects_allocated_delta
  orig = GC.stat(:total_allocated_object)
  yield
  puts "#{GC.stat(:total_allocated_object) - orig} objects allocated"
end

2.1.0p0 :006 > log_gc_objects_allocated_delta do; nil; end
0 objects allocated
 => nil 
2.1.0p0 :007 > log_gc_objects_allocated_delta do; []; end
1 objects allocated
 => nil 

We are intentionally not taking into account :total_freed_object there, because our goal is to just see how many objects were allocated.

And, please note that, according to the Ruby 2.1 API: "The contents of the hash are implementation specific and may be changed in the future. This method is only expected to work on C Ruby."

No comments: