이러한 종류의 것들을 테스트하려면 Benchmark module을 사용할 수 있습니다. 그래서처럼 원래의 코드에 대해 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
은 배열이 다소 크고 작업이 여러 번 수행되는 경우 수동으로 배열에 추가하는 것보다 훨씬 빠릅니다.
고마워, 그게 정말 유용한 답변이야! – ktec
당신을 진심으로 환영합니다! 그냥 도와 줘서 고마워. :) –