Writing Fast Ruby by Erik Michaels-Oberのまとめ。
!!!基本的に用途が違うもの同士を比較しています。間違っても、「こう書いた方が速いらしいからこう書こう」とは思わないでください!!!
Proc#call 対 yield
=begin
* Proc#call vs yield
* yield が5倍以上速い
=end
def slow(&block)
block.call
end
def fast
yield
end
Block 対 Symbol#to_proc
=begin
* Block 対 Symbol#to_proc
* Symbol#to_proc が20%速い
=end
def slow
(1..100).each {|i| i.to_s }
end
def fast
(1..100).each {$:to_s}
end
Enumerable#map and Array#flatten 対 Enumerable#flat_map
=begin
* Enumerable#map and Array#flatten 対 Enumerable#flat_map
* Enumerable#flat_map が4.5倍以上速い
=end
enum.map do
#do something
end.flatten(1)
enum.flat_map do
#do something
end
Hash#merge 対 Hash#merge!
=begin
* Hash#merge 対 Hash#merge!
* Hash#merge! が3倍以上速い
=end
enum.inject({}) do |h, e|
h.merge(e => e)
end
enum.inject({}) do |h, e|
h.merge!(e => e)
end
Hash#merge! 対 Hash#[]=
=begin
* Hash#merge! 対 Hash#[]=
* Hash#[]= が2倍以上速い
=end
enum.each_with_object({}) do |h, e|
h.merge!(e => e)
end
enum.each_with_object({}) do |h, e|
h[e] = e
end
Hash#fetch 対 Hash#fetch with block
=begin
* Hash#fetch 対 Hash#fetch with block
* Hash#fetch with block が2倍以上速い
=end
{ :rails => :club }.fetch(:rails, (0..9).to_a)
{ :rails => :club }.fetch(:rails){ (0..9).to_a }
String#gsub 対 String#sub
=begin
* String#gsub 対 String#sub
* String#sub が5割速い
=end
"http://railsclub.com".gsub("http://","https://")
"http://railsclub.com".sub("http://","https://")
String#gsub 対 String#tr
=begin
* String#gsub 対 String#tr
* String#tr が5倍以上速い
=end
"slug grom title".gsub(" ", "_")
"slug grom title".tr(" ", "_")
並列代入 対 個別代入
=begin
* 並列代入 対 個別代入
* 個別代入が4割速い
=end
def slow
a, b = 1, 2
end
def fast
a = 1
b = 2
end
例外処理 対 条件分岐
=begin
* 例外処理 対 条件分岐
* 条件分岐入が10倍以上速い
* (まあそうだろうけど…)
=end
begin
rails
rescue NoMethodError
club
end
if respond_to?(:rails)
rails
else
club
end
Array#each_with_index 対 while文
=begin
* Array#each_with_index 対 while文
* while文が8割速い
* (いやさ…)
=end
ary.each_with_index do |num. index|
# do something with num & index
end
index = 0
while index < ary.size
# do something with num & index
index += 1
end