DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby Object Creation Tracer

05.26.2006
| 3371 views |
  • submit to reddit
        Slap this stuff at the top of your code and it will tell you where most of your objects are being created. 

http://wiki.rubygarden.org/Ruby/page/show/NewProfiler

 class Class
  alias_method :orig_new, :new

  @@count = 0
  @@stoppit = false
  @@class_caller_count = Hash.new{|hash,key| hash[key] = Hash.new(0)}

  def new(*arg,&blk)
    unless @@stoppit
      @@stoppit = true
      @@count += 1
      @@class_caller_count[self][caller[0]] += 1
      @@stoppit = false
    end
    orig_new(*arg,&blk)
  end

  def Class.report_final_tally
    @@stoppit = true
    puts "Number of objects created = #{@@count}"

    total = Hash.new(0)
    
    @@class_caller_count.each_key do |klass|
      caller_count = @@class_caller_count[klass]
      caller_count.each_value do |count|
        total[klass] += count
      end
    end
    
    klass_list = total.keys.sort{|klass_a, klass_b| 
      a = total[klass_a]
      b = total[klass_b]
      if a != b
        -1* (a <=> b)
      else
        klass_a.to_s <=> klass_b.to_s
      end
    }
    klass_list.each do |klass|
      puts "#{total[klass]}\t#{klass} objects created."
      caller_count = @@class_caller_count[ klass]
      caller_count.keys.sort_by{|call| -1*caller_count[call]}.each do |call|
        puts "\t#{call}\tCreated #{caller_count[call]} #{klass} objects."
      end
      puts
    end
  end
 end

 END {
  b = String.new
  Class.report_final_tally
 }