Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nahi
Forked from shugo/CRuby
Created April 24, 2012 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nahi/2477038 to your computer and use it in GitHub Desktop.
Save nahi/2477038 to your computer and use it in GitHub Desktop.
new vs mutation in Ruby
require "benchmark"
TIMES = 5_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
c = 0
while c < TIMES
Node.new(:B, nil, 0, nil)
c += 1
end
end
bm.report("color=") do
c = 0
while c < TIMES
node.color = :B
c += 1
end
end
end
% jruby -v --server -X+C benchmark_new.rb
jruby 1.7.0.dev (ruby-1.9.3-p139) (2012-04-24 6a30d22) (Java HotSpot(TM) 64-Bit Server VM 1.7.0_03) [linux-amd64-java]
Rehearsal ------------------------------------------
new 1.290000 0.110000 1.400000 ( 0.974000)
color= 0.200000 0.010000 0.210000 ( 0.172000)
--------------------------------- total: 1.610000sec
user system total real
new 0.760000 0.000000 0.760000 ( 0.663000)
color= 0.160000 0.000000 0.160000 ( 0.133000)
% ruby -v benchmark_new.rb
ruby 2.0.0dev (2012-04-24 trunk 35453) [x86_64-linux]
Rehearsal ------------------------------------------
new 2.780000 0.000000 2.780000 ( 2.792829)
color= 0.360000 0.000000 0.360000 ( 0.363622)
--------------------------------- total: 3.140000sec
user system total real
new 2.710000 0.000000 2.710000 ( 2.718985)
color= 0.370000 0.000000 0.370000 ( 0.372109)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment