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?
present tense third-person singular of do.
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.
“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 definition. Filters. (slang) What's up? What's going on? interjection.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With