Issue #8909 has been updated by headius (Charles Nutter).


@matz What I mean is that all of the following could safely be optimized to return the same object every time:

[]f
{}f
[:foo, 1, 1.5, true, nil]

I cannot decide whether restricting the elements to be literals and/or statically frozen is a good idea or not. For example, something like this seems like it should be acceptable:

{cache: ThreadSafe::Hash.new}

It wouldn't be able to optimize to be the same object every time, but it would still be a frozen Hash and nobody downstream could change the keys/values it stores.

So I guess the question is whether shallow freeze with potentially mutable elements is good or not.

Pros and cons:

3. Shallow freeze, no restrictions

+ simplest to implement
+ most flexible
+ no side effects
- mutable elements are still mutable
- user may expect elements to freeze too

2. Shallow freeze, only frozen or literals as elements

+ prevents unintentional exposure of mutable elements in frozen collection
+ no side effects due to deep freezing
- less flexible
- user may want elements to be unfrozen
- more complicated to implement
- frozen elements may have unfrozen elements

1. Deep freeze

+ Guarantees everything inside frozen collection is deep-frozen
+ May reflect frozen modifier more clearly
+ Less typing to freeze all elements
- Most complicated and no existing functionality
- Array/Hash creation would deep freeze objects as side effect
- May have unintended consequences

I'm still leaning toward #1.
----------------------------------------
Feature #8909: Expand "f" frozen suffix to literal arrays and hashes
https://bugs.ruby-lang.org/issues/8909#change-41839

Author: headius (Charles Nutter)
Status: Feedback
Priority: Normal
Assignee: 
Category: 
Target version: 


The "f" suffix to declare a frozen string was recently accepted into 2.1, and I think it's a spectacular addition. I would very much like to see it work for literal arrays and hashes too:

[1, 2, 3, 4, 5]f

{foo: 1, bar: 2, baz: 3}f

There are many, many cases where this could reduce allocation (frozen array with literal elements would only need to be allocated once) and improve thread-safety (explicitly create frozen arrays and hashes when creating structures that might be used across threads).

Is there any reason why we could not do this? I believe both of the above syntaxes would be invalid today, as was the case with the String "f" suffix, and hopefully that means the work to add this syntax would be similar.


-- 
http://bugs.ruby-lang.org/