Search code examples
rubyconstructorruby-1.9.3splat

Is it effcient to use a splat operator in a constructor?


In a constructor, it often happens that you want to turn the arguments into instance variables. A naive way to do it is:

class A
    def initialize a, b, c
        @a, @b, @c = a, b, c
    end
end

but an easier way is:

class A
    def initialize *args
        @a, @b, @c = args
    end
end

But I was concerned about the speed of the code since it looks like the latter code is creating an extra array args that was not created in the former code. From the point of view of the speed or efficienty, is the better to stick to the former one and not use the latter one, or is there no difference?


Solution

  • Looks fine from here:

    RUBY_VERSION # => "1.9.3"
    
    def set_each(a,b,c)
      a2, b2, c2 = a, b, c
    end
    
    def set_ary(*args)
      a2, b2, c2 = args
    end
    
    def time(n)
      start_time = Time.now
      n.times { yield }
      Time.now - start_time
    end
    
    n = 1_000_000
    time(n) { set_each 1, 2, 3 } # => 0.301268
    time(n) { set_ary 1, 2, 3 }  # => 0.308298