在构造函数中使用 splat 运算符是否有效?

发布于 2025-01-06 04:42:02 字数 363 浏览 7 评论 0原文

在构造函数中,经常需要将参数转换为实例变量。一个简单的方法是:

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

但更简单的方法是:

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

但我担心代码的速度,因为它看起来后面的代码正在创建一个额外的数组 args ,该数组不是在以前的代码。从速度或效率的角度来看,是坚持前一种而不使用后一种更好,还是没有区别?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我的奇迹 2025-01-13 04:42:02

从这里看起来不错:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文