LoginSignup
4
4

More than 5 years have passed since last update.

Rubyでのシングルクォーテーションとダブルクォーテーションの性能差異について

Last updated at Posted at 2016-04-04

Rubyでのシングルクォーテーションとダブルクォーテーションの性能差異について

はじめに

PHPでprintやechoする際、ダブルクォーテーションで括ってあげると式展開ができる。
もっと言うとシングルクォーテーションで括っても式展開はできず、
ダブルクォーテーションで括った場合は、式展開をする処理が動く。

(わざわざ言うことでもない気もしますが)
なので、以下のように変数を含む場合と含まない場合とで、
シングルクォーテーションで書くよう、考慮してる。

PHP
print 'Hello.';
print "Hello $name";

では、Rubyではどうなの?という疑問から、
若干性能について見てみる。

評価

狂ったように10,000,000回、まわしてみる。
(Ruby標準のパッケージを利用する)

require 'benchmark'

start_time = Time.now
result = Benchmark.realtime do
  for num in 1...10000000
    print 'performance.'
    # print "performance."

  end
end

print result

結果

シングルクォーテーション ダブルクォーテーション
234.6442553200177 295.6961059400346

まとめ

PHPやRubyのソースまでは追ってないが、式展開する処理が動く分、
ダブルクォーテーションの方が処理時間がかかることがわかる。
重い処理や繰り返し処理をする際は、気をつけたほうがよさ気ですねー。

4
4
2

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
4
4