Juste pour tester la méthode collect, suite à un article sur Ruby's Cube...
Le code :
(testé sous Windows XP ; Ruby 1.8.6)
Le code :
(testé sous Windows XP ; Ruby 1.8.6)
# Benchmark for using collect
#or naive method on enumerable.
users = ["toto", "titi", "tartempion"]
# Naive method
def meth1(users)
names = ""
for user in users
names << "#{user} "
end
return names.chomp
end
# Collect is flashy !
def meth2(users)
names = users.collect { |user| user}
return names.join(' ')
end
# Benchmark
require 'benchmark'
Benchmark.bm(15) do |timer|
timer.report('Barbarian method') {
for i in (0...1000)
meth1 users
end
}
timer.report("Ruby's finest...") {
for i in (0...1000)
meth2 users
end
}
end
#~ user system total real
#~ Barbarian method 0.016000 0.000000 0.016000 ( 0.016000)
#~ Ruby's finest... 0.000000 0.000000 0.000000 ( 0.000000)
1 commentaires:
Comme quoi "collect()" c'est vraiment bien ;)
Enregistrer un commentaire