在 Ruby 中从对象数组中提取嵌套对象数组的快速方法是什么?>

发布于 2024-09-07 18:18:02 字数 192 浏览 1 评论 0原文

我有一个元素数组,每个元素都有一个属性: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 技术交流群。

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

发布评论

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

评论(2

一枫情书 2024-09-14 18:18:02
elements.map {|element| element.image}

这应该与您的版本具有大致相同的性能,但更简洁、更惯用。

elements.map {|element| element.image}

This should have about the same performance as your version, but is somewhat more succinct and more idiomatic.

浅语花开 2024-09-14 18:18:02

您可以使用 Benchmark 模块 来测试此类内容。我针对您的原始代码运行了 @sepp2k 的版本,如下所示:

require 'benchmark'

class Element
  attr_accessor :image

  def initialize(image)
    @image = image
  end
end

elements = Array.new(500) {|index| Element.new(index)}

n = 10000

Benchmark.bm do |x|
  x.report do
    n.times do
      # Globalkeith's version
      image = []
      elements.each {|element| image << element.image}
    end
  end
  # sepp2k's version
  x.report { n.times do elements.map {|element| element.image} end }
end

我的机器上的输出始终(超过 3 次运行后)非常接近于此:

   user     system      total        real
2.140000   0.000000   2.140000 (  2.143290)
1.420000   0.010000   1.430000 (  1.422651)

因此证明 map 是当数组较大并且操作执行多次时,比手动追加到数组要快得多。

You can use the Benchmark module to test these sorts of things. I ran @sepp2k's version against your original code like so:

require 'benchmark'

class Element
  attr_accessor :image

  def initialize(image)
    @image = image
  end
end

elements = Array.new(500) {|index| Element.new(index)}

n = 10000

Benchmark.bm do |x|
  x.report do
    n.times do
      # Globalkeith's version
      image = []
      elements.each {|element| image << element.image}
    end
  end
  # sepp2k's version
  x.report { n.times do elements.map {|element| element.image} end }
end

The output on my machine was consistently (after more than 3 runs) very close to this:

   user     system      total        real
2.140000   0.000000   2.140000 (  2.143290)
1.420000   0.010000   1.430000 (  1.422651)

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.

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