Last active
August 29, 2015 14:05
-
-
Save elskwid/b1c278d64dcdf8562dfb to your computer and use it in GitHub Desktop.
Object allocation using literals vs. constants
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@elskwid also check out benchmark-ips for cases like this.