I have an array of Elements, and each element has a property :image.
我有一个元素数组,每个元素都有一个属性: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}
2 个解决方案
#1
3
You can use the Benchmark module to test these sorts of things. I ran @sepp2k's version against your original code like so:
您可以使用基准模块来测试这些类型的东西。我运行@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
The output on my machine was consistently (after more than 3 runs) very close to this:
我的机器上的输出始终(经过3次以上)非常接近这个:
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.
因此,当数组比较大,并且多次执行操作时,演示map比手工附加到数组的速度要快得多。
#2
5
elements.map {|element| element.image}
This should have about the same performance as your version, but is somewhat more succinct and more idiomatic.
这应该与您的版本具有相同的性能,但更简洁,更地道。
#1
3
You can use the Benchmark module to test these sorts of things. I ran @sepp2k's version against your original code like so:
您可以使用基准模块来测试这些类型的东西。我运行@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
The output on my machine was consistently (after more than 3 runs) very close to this:
我的机器上的输出始终(经过3次以上)非常接近这个:
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.
因此,当数组比较大,并且多次执行操作时,演示map比手工附加到数组的速度要快得多。
#2
5
elements.map {|element| element.image}
This should have about the same performance as your version, but is somewhat more succinct and more idiomatic.
这应该与您的版本具有相同的性能,但更简洁,更地道。