Skip to content

Instantly share code, notes, and snippets.

@shugo
Created April 23, 2012 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shugo/2467749 to your computer and use it in GitHub Desktop.
Save shugo/2467749 to your computer and use it in GitHub Desktop.
new vs mutation in Ruby
require "benchmark"
TIMES = 1_000_000
class Node
attr_accessor :color, :left, :value, :right
def initialize(color, left, value, right)
@color = color
@left = left
@value = value
@right = right
end
end
node = Node.new(:R, nil, 0, nil)
Benchmark.bmbm do |bm|
bm.report("new") do
TIMES.times do |i|
Node.new(:B, nil, 0, nil)
end
end
bm.report("color=") do
TIMES.times do |i|
node.color = :B
end
end
end
$ ruby-trunk -v benchmark_new.rb
ruby 2.0.0dev (2012-04-18 trunk 35385) [i686-linux]
Rehearsal ------------------------------------------
new 1.030000 0.000000 1.030000 ( 1.035411)
color= 0.180000 0.000000 0.180000 ( 0.180050)
--------------------------------- total: 1.210000sec
user system total real
new 1.010000 0.010000 1.020000 ( 1.008668)
color= 0.180000 0.000000 0.180000 ( 0.181044)
$ jruby --1.9 -v benchmark_new.rb
jruby 1.6.7 (ruby-1.9.2-p312) (2012-02-22 3e82bc8) (OpenJDK Server VM 1.6.0_23) [linux-i386-java]
Rehearsal ------------------------------------------
new 0.790000 0.000000 0.790000 ( 0.790000)
color= 0.241000 0.000000 0.241000 ( 0.241000)
--------------------------------- total: 1.031000sec
user system total real
new 0.333000 0.000000 0.333000 ( 0.333000)
color= 0.154000 0.000000 0.154000 ( 0.154000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment