4

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?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
sawa
  • 165,429
  • 45
  • 277
  • 381
  • not really an answer, but I would suggest writing a test program that instantiates thousands of objects using each constructor definition. comparing the time for each to finish will yield the faster of the two implementations. – ardnew Feb 15 '12 at 22:46
  • I know you are concerned specifically with speed, but given that the second snippet throws away vital information (the arguments of the method), it's hard to see why would one write it that way... – tokland Feb 15 '12 at 23:11

1 Answers1

5

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
Joshua Cheek
  • 30,436
  • 16
  • 74
  • 83