I was always under the impression that parallel assignments in Ruby
were faster than assigning variables individually.
Recently I was curious to see how much faster it was and decided to
test it:
class One
def initialize(first_name, last_name) @first_name = first_name @last_name = last_name
end
end
class Two
def initialize(first_name, last_name) @first_name, @last_name = first_name, last_name
end
end
require “rubygems”
require “benchmark”
Benchmark.bmbm do |test|
test.report(“serial”) do
10000.times { |n| var = One.new(“gavin#{n}”, “morrice”)}
end
test.report(“parallel”) do
10000.times { |n| var = Two.new(“gavin#{n}”, “morrice”)}
end
end
The results I get show that it’s slower (in both Ruby 1.8.7 and Ruby
1.9.1)
end
def initialize(*args) @first_name, @last_name = *args
end
end
I have a class Three cause I was also testing this other form, which
also creates arrays:
GC.disable
puts “Arrays before serial: #{ObjectSpace.each_object(Array){}}”
10000.times { |n| var = One.new(“gavin#{n}”, “morrice”)}
puts “Arrays after serial: #{ObjectSpace.each_object(Array){}}”
10000.times { |n| var = Two.new(“gavin#{n}”, “morrice”)}
puts “Arrays after parallel: #{ObjectSpace.each_object(Array){}}”
10000.times { |n| var = Three.new(“gavin#{n}”, “morrice”)}
puts “Arrays after parallel with array:
#{ObjectSpace.each_object(Array){}}”
$ ruby test_parallel_assignment.rb
Arrays before serial: 3589
Arrays after serial: 3589
Arrays after parallel: 13589
Arrays after parallel with array: 23589
Yep, that was my thought and that’s why I checked with ObjectSpace,
that indeed shows Arrays being created.
It was easier for me than checking the implementation :-).
I think it might be because the parallel assigment creates an array
under the hood?
However it is done technically, parallel assignment needs more space
because it has to evaluate all right hand sides before doing any
assignments. Otherwise swapping would not be possible
a, b = b, a
So, yes, it’s likely an Array under the hood but even if not the
parallel assignment of two variables needs to store two object
references while sequential assignments of an arbitrary number of
elements gets away with space for a single reference (if you need it at
all).
Kind regards
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.