Skip to content

Instantly share code, notes, and snippets.

@austra
Created March 16, 2017 16:41
Show Gist options
  • Save austra/43de145033ab881cf0012ed942504848 to your computer and use it in GitHub Desktop.
Save austra/43de145033ab881cf0012ed942504848 to your computer and use it in GitHub Desktop.
Ruby Benchmark with ObjectSpace
require 'objspace'
require 'benchmark'
Benchmark.bmbm do |bm|
bm.report("using [] :") do
GC.start
mem_before = ObjectSpace.memsize_of_all
before = GC.stat[:total_allocated_objects]
1000.times do |i|
user = User.where(username: "asdf")
user.any?
end
mem_after = ObjectSpace.memsize_of_all
after = GC.stat[:total_allocated_objects]
puts "Allocations: #{after - before} - Memory: #{mem_after - mem_before}"
end
bm.report("using merge :") do
GC.start
mem_before = ObjectSpace.memsize_of_all
before = GC.stat[:total_allocated_objects]
1000.times do |i|
user = User.where(username: "asdf")
user.none?
end
mem_after = ObjectSpace.memsize_of_all
after = GC.stat[:total_allocated_objects]
puts "Allocations: #{after - before} - Memory: #{mem_after - mem_before}"
end
end
Benchmark.bmbm do |bm|
bm.report('using += :') do
str = "so"
100000.times do { str += " this is slower " }
end
bm.report('using << :' do
str = "so"
100000.times do { str << " this is faster " }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment