Skip to content

Instantly share code, notes, and snippets.

@elskwid
Last active August 29, 2015 14:05
Show Gist options
  • Save elskwid/b1c278d64dcdf8562dfb to your computer and use it in GitHub Desktop.
Save elskwid/b1c278d64dcdf8562dfb to your computer and use it in GitHub Desktop.
Object allocation using literals vs. constants
require "benchmark"
require "gc_tracer"
include Process
class WithLiteral
def call
[]
end
end
class WithConstant
EMPTY_ARRAY = []
def call
EMPTY_ARRAY
end
end
class WithFrozenConstant
EMPTY_ARRAY = [].freeze
def call
EMPTY_ARRAY
end
end
n = 10_000_000
run = ->(ex) { n.times { ex.new.call } }
gc_report = lambda do |label|
s = GC.stat
allocated = s[:total_allocated_object]
freed = s[:total_freed_object]
live = s[:heap_live_slot]
<<-REPORT
#{label} GC stats:
Allocated: #{allocated}
Freed: #{freed}
Live: #{live}
REPORT
end
[WithLiteral, WithConstant, WithFrozenConstant].each do |ex|
fork do
start_report = ""
end_report = ""
Benchmark.bm do |bm|
bm.report(ex.to_s) do
start_report = gc_report.("#{ex} start")
run.(ex)
end_report = gc_report.("#{ex} end")
end
puts "", start_report, ""
puts end_report, ""
end
end # fork
wait # for forked process
end
> ruby lib/benchmarks/object_allocation.rb
user system total real
WithLiteral 2.930000 0.000000 2.930000 ( 3.018267)
WithLiteral start GC stats:
Allocated: 49483
Freed: 17301
Live: 32182
WithLiteral end GC stats:
Allocated: 20049491
Freed: 20016504
Live: 32987
user system total real
WithConstant 2.290000 0.000000 2.290000 ( 2.327953)
WithConstant start GC stats:
Allocated: 49484
Freed: 17301
Live: 32183
WithConstant end GC stats:
Allocated: 10049492
Freed: 10016489
Live: 33003
user system total real
WithFrozenConstant 2.300000 0.000000 2.300000 ( 2.315593)
WithFrozenConstant start GC stats:
Allocated: 49485
Freed: 17301
Live: 32184
WithFrozenConstant end GC stats:
Allocated: 10049493
Freed: 10016489
Live: 33004
@phlipper
Copy link

@elskwid also check out benchmark-ips for cases like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment