6
6

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 5 years have passed since last update.

文字列リテラルをfreezeすると共有の定数になる

Posted at

ruby 2.1 から文字列リテラルをfreezeすると、一つの定数としてオブジェクトが共有されてオブジェクトが無駄に増えないようになっているそうです。(Effective Ruby 参照)
freezeよりも文字列の生成が先なのに、なぜ増えないのか不思議です。
共有されるのは「文字列のみ」のようです。Hashで試したら定数にはなりませんでした。

X = "x".freeze
N = 100000

GC.enable
GC.start
GC.disable
N.times { "x" }
ObjectSpace.each_object(String).count {|e| e == X } # => 100002

GC.enable
GC.start
GC.disable
N.times { "x".freeze }
ObjectSpace.each_object(String).count {|e| e == X } # => 2

X.object_id == "x".freeze.object_id # => true

N.times.collect {|e| "x".freeze.object_id }.uniq.count # => 1

RUBY_VERSION                    # => "2.2.2"
6
6
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?