0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rubyではシンボルと文字列ならシンボルの方が早い

Posted at

概要

Rubyで、大量の文字列とシンボルを比較する際にはシンボルの方が早い。

シンボルの特徴

####Ruby内部で文字列でなく整数として扱われるので、早い。
比較検索の際に、有利なのでハッシュのキー、メソッドへの引数に使える。

####イミュータブルなオブジェクトである。
破壊的変更を意図したくない場合に使える。

計算

require 'benchmark'

Benchmark.bm 10 do |r|

  fruits = ['apple','orange','lemon']

  r.report 'string' do
    target = 'orange'
    fruits.each {|fruit| fruit == target}
  end

  r.report 'symbol' do
    target = :orange
    fruits.each {|fruit| fruit == target}
  end
end

##結果

                 user     system      total        real
string       0.000014   0.000014   0.000028 (  0.000012)
symbol       0.000006   0.000001   0.000007 (  0.000006)

参考
Rubyの文字列とシンボルの違いをキッチリ説明できる人になりたい
Rubyのシンボルは文字列の皮を被った整数だ!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?