Skip to content

Instantly share code, notes, and snippets.

@justincampbell
Last active August 29, 2015 13:57
Show Gist options
  • Save justincampbell/9493819 to your computer and use it in GitHub Desktop.
Save justincampbell/9493819 to your computer and use it in GitHub Desktop.
.allocate vs .new
puts RUBY_DESCRIPTION
require 'benchmark'
count = (ARGV[0] || 1_000_000).to_i
class Thing
def foo
:bar
end
end
Thing.new
Thing.allocate
Benchmark.bm(7) do |bm|
bm.report :new do
count.times do
Thing.new.foo
end
end
bm.report :allocate do
count.times do
Thing.allocate.foo
end
end
end
$ for ruby in 1.9 2.0 2.1; do chruby $ruby; ruby allocate_vs_new.rb; done
ruby 1.9.3p545 (2014-02-24 revision 45159) [x86_64-darwin13.0.0]
user system total real
new 0.270000 0.000000 0.270000 ( 0.277544)
allocate 0.210000 0.000000 0.210000 ( 0.203312)
ruby 2.0.0p451 (2014-02-24 revision 45167) [x86_64-darwin13.0.0]
user system total real
new 0.240000 0.010000 0.250000 ( 0.249500)
allocate 0.220000 0.000000 0.220000 ( 0.215938)
ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin13.0]
user system total real
new 0.180000 0.000000 0.180000 ( 0.188794)
allocate 0.150000 0.010000 0.160000 ( 0.143627)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment