Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does #freeze have a use other than preventing modification?

Tags:

ruby

Ruby's standard uri library has many uses of freeze on objects which either can't be modified, or where modification will cause no harm:

  user, password = ui.split(':'.freeze, 2)     # from generic.rb

String#split won't modify its arguments, and even if it did, the code would work properly (Ruby will use a new instance of ':' on the next call).

Here are some more uses of freeze on objects that can't change (these are all from generic.rb)

 if @scheme && @scheme != "ftp".freeze 
 v.delete!("\t\r\n".freeze)
 str << ':'.freeze 

Why are there so many instances of seemingly needless calls to #freeze? Does #freeze have a use beyond preventing modification of its receiver?

like image 879
Wayne Conrad Avatar asked Jul 31 '15 21:07

Wayne Conrad


People also ask

What you mean by does?

present tense third-person singular of do.

Does definition and examples?

Does references the performance or achievements of another. An example of does is telling a friend that your husband is in marketing, "He does marketing." Plural form of doe. Third-person singular simple present indicative form of do.

Do it or does it?

“Does” is used for singular subjects like “he,” “she,” “it,” “this,” “that,” or “John.” “Do” is used to form imperative sentences, or commands. Example: Do your homework. “Does” is never used to form imperative sentences.

What it do meaning?

What-it-do definition. Filters. (slang) What's up? What's going on? interjection.


1 Answers

The answer to this question can be found here: http://tmm1.net/ruby21-fstrings/

In Ruby 2.1, "str".freeze is optimized by the compiler to return a single shared frozen strings on every invocation. An alternative "str"f syntax was implemented initially, but later reverted.

Although the external scope of this feature is limited, internally it is used extensively to de-duplicate strings in the VM. Previously, every def method_missing(), the symbol :method_missing and any literal "method_missing" strings in the code-base would all create their own String objects. With Ruby 2.1, only one string is created and shared. Since many strings are commonly re-used in any given code base, this easily adds up. In fact, large applications can expect up to 30% fewer long-lived strings on their heaps in 2.1.

For 2.2, there are plans to expose this feature via a new String#f. There's also a proposal for a magic immutable: string comment to make frozen strings default for a given file.

TL;DR: the Ruby parser treats a string literal with .freeze after it differently than a string literal without the .freeze. Strings with .freeze will not be re-instantiated every time they are used, but instead will come from a global frozen string pool like symbols.

Here is a more in-depth article on the subject: http://josephyi.com/freeze/

like image 76
Adrian Avatar answered Nov 15 '22 06:11

Adrian