lambda 有哪些缺点?

发布于 2024-09-28 06:15:08 字数 367 浏览 2 评论 0原文

我经常喜欢这样做:

a, b = lambda do |data|
    [f1(data), f2(data)]
end.call(some_function(some_data))

而不是这样:

data = some_function(some_data))
a, b = f1(data), f2(data)

或这样:

a, b = f1(some_function(some_data)), f2(some_function(some_data))

对几乎所有事情使用 lambda 是否会产生负面后果?

I often prefer to do this:

a, b = lambda do |data|
    [f1(data), f2(data)]
end.call(some_function(some_data))

instead of this:

data = some_function(some_data))
a, b = f1(data), f2(data)

or this:

a, b = f1(some_function(some_data)), f2(some_function(some_data))

Is there any negative consequence from using lambdas for almost every single thing?

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

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

发布评论

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

评论(2

紫瑟鸿黎 2024-10-05 06:15:08

主要后果是 Ruby 程序员不太习惯这样做。您的任何一种选择都更容易被社区成员、团队的其他成员、未来的维护者等阅读。

第二个结果是,以这种方式创建一次性 lambda 函数将比调用静态函数慢。创建 lambda 无论如何都不是特别慢,但仍然比不使用它们慢。如果你经常这样做,它就会开始累加。为了提供一些背景信息,创建空 lambda 所需的时间大约是创建空数组的 10 倍。因此,如果您重复执行此操作(例如,在反复使用的函数调用内),则差异可能会增加。

最后,至少还有另一种方法可以做到这一点。我确信其他一些也存在......

a, b = [:f1, :f2].collect { |fn| send(fn, some_function(some_data)) }

不过,总而言之,我认为你的第一个选择是最干净的方法:

data = some_function(some_data)
a, b = f1(data), f2(data)

它完全清楚你在做什么,而且也很高效。

The principal consequence is Ruby programmers aren't particularly accustomed to doing it this way. Either one of your alternatives would be more easily readable by members of the community, other members of your team, future maintainers, etc.

The secondary consequence is creating one-off lambda functions in this way will be slower than calling static functions. Creating lambdas aren't extraordinarily slow by any means, but it's still slower than not using them. If you did this a lot, it would start to add up. To give some context, creating an empty lambda takes about 10 times longer to create than an empty array. So if you were doing this repeatedly (e.g. inside a function call that gets used over and over), that difference could add up.

Lastly, there is at least one other way to do it. I'm sure some others exist, too...

a, b = [:f1, :f2].collect { |fn| send(fn, some_function(some_data)) }

All in all, though, I think your first alternative is the cleanest approach:

data = some_function(some_data)
a, b = f1(data), f2(data)

It's entirely clear what you're doing and is also efficient.

演出会有结束 2024-10-05 06:15:08

我还不能发表评论,所以我只是模仿 Wuputah,他是对的。我看过的每一个 Ruby 优化视频和我读过的每本书都说要避免使用 lambda,除非您绝对需要它们,因为当您尝试扩展应用程序时,它们可能会对性能造成巨大影响。这并不是说您不应该使用它们,只是不要滥用它们。

I can't comment yet so I'm just going to mirror Wuputah, he's right. Every single Ruby optimization video I've watched and every book I've read has said to avoid lambdas unless you absolutely need them because they can be huge performance hits when you try to scale your app. This isn't to say you shouldn't use them, just don't abuse them.

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