在 Ruby 中从对象数组中提取嵌套对象数组的快速方法是什么?>
我有一个元素数组,每个元素都有一个属性:image。
我想要一组:图像,那么实现此目的最快且最便宜的方法是什么。是否只是迭代数组并将每个元素推入一个新数组,如下所示:
images = []
elements.each {|element| images << element.image}
I have an array of Elements, and each element has a property :image.
I would like an array of :images, so whats the quickest and least expensive way to achieve this. Is it just iteration over the array and push each element into a new array, something like this:
images = []
elements.each {|element| images << element.image}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该与您的版本具有大致相同的性能,但更简洁、更惯用。
This should have about the same performance as your version, but is somewhat more succinct and more idiomatic.
您可以使用 Benchmark 模块 来测试此类内容。我针对您的原始代码运行了 @sepp2k 的版本,如下所示:
我的机器上的输出始终(超过 3 次运行后)非常接近于此:
因此证明
map
是当数组较大并且操作执行多次时,比手动追加到数组要快得多。You can use the Benchmark module to test these sorts of things. I ran @sepp2k's version against your original code like so:
The output on my machine was consistently (after more than 3 runs) very close to this:
Thus demonstrating that
map
is significantly faster than manually appending to an array when the array is somewhat large and the operation is performed many times.