2

Following development of Ruby 2.1 I have read about a feature that will probably be added so a developer is allowed to specify that a literal String should start out "frozen".

The syntax looks like this (note the trailing f):

str = "imfrozen"f    # str receives a frozen string

In other Ruby documentation/wiki i've read that this feature provides the following benefit:

This allows the VM to use the same String object each time, and potentially for the same frozen string across many files. It also obviously provides all the immutability guarantees of a frozen string.

My questions are:

  • What is the benefit of this?
  • What is a real world example of when a feature like this would provide value?
  • How is this different from a symbol ?

Thank you

CharlesHorse
  • 449
  • 1
  • 4
  • 9

1 Answers1

7

Suppose you had code like this

array_that_is_very_long.each do |e|
  if e == "foo"
    ...
  end
end

In this code, for each iteration over array_that_is_very_long, a new string "foo" is created (and is thrown out), which is a huge waste of resource. Currently, you can overcome this problem by doing:

Foo = "foo"
array_that_is_very_long.each do |e|
  if e == Foo
    ...
  end
end

The proposed syntax makes this easier to do as so:

array_that_is_very_long.each do |e|
  if e == "foo"f
    ...
  end
end
sawa
  • 165,429
  • 45
  • 277
  • 381
  • thank you very much. These code samples make it very clear how it could be used. What would the benefit be though? Smaller memory footprint? Faster execution? Why wouldn't you use a symbol? – CharlesHorse Oct 03 '13 at 22:48
  • If `e` a string, there is no reason to convert if into a symbol and compare it as a symbol unless there is particular use of it in other parts of the code. – sawa Oct 03 '13 at 23:07