From: eregontp@... Date: 2019-09-10T08:12:28+00:00 Subject: [ruby-core:94885] [Ruby master Feature#16150] Add a way to request a frozen string from to_s Issue #16150 has been updated by Eregon (Benoit Daloze). I tried running ActiveSupport tests from Rails master on Ruby 2.6.2 + my PR, and found that one change is needed: ``` Error: ConfigurableActiveSupport#test_configuration_accessors_are_not_available_on_instance: FrozenError: can't modify frozen String /home/eregon/code/rails/activesupport/lib/active_support/ordered_options.rb:43:in `chomp!' /home/eregon/code/rails/activesupport/lib/active_support/ordered_options.rb:43:in `method_missing' ... ``` https://github.com/rails/rails/blob/7af44f49dbf221c3b7f0b0d476913a74b6a1d0e4/activesupport/lib/active_support/ordered_options.rb#L42-L43 A simple fix is to use `name_string = +name.to_s`, or to refactor to use `start_with?` + `name_string[0..-2]` instead of `chomp!`. Then all ActiveSupport tests pass. ---------------------------------------- Feature #16150: Add a way to request a frozen string from to_s https://bugs.ruby-lang.org/issues/16150#change-81500 * Author: headius (Charles Nutter) * Status: Open * Priority: Normal * Assignee: * Target version: ---------------------------------------- Much of the time when a user calls to_s, they are just looking for a simple string representation to display or to interpolate into another string. In my brief exploration, the result of to_s is rarely mutated directly. It seems that we could save a lot of objects by providing a way to explicitly request a *frozen* string. For purposes of discussion I will call this to_frozen_string, which is a terrible name. This would reduce string allocations dramatically when applied to many common to_s calls: * Symbol#to_frozen_string could always return the same cached String representation. This method is *heavily* used by almost all Ruby code that intermingles Symbols and Strings. * nil, true, false, and any other singleton values in the system could similarly cache and return the same String object. * The strings coming from core types could also be in the fstring cache and deduplicated as a result. * User-provided to_s implementations could opt-in to caching and returning the same frozen String object when the author knows that the result will always be the same. A few ideas for what to call this: * `to_fstring` or `fstring` reflects internal the "fstring" cache but is perhaps not obvious for most users. * `to_s(frozen: true)` is clean but there will be many cases when the kwargs hash doesn't get eliminated, making matters worse. * `def to_s(frozen = false)` would be mostly free but may not be compatible with existing to_s params (like `Integer#to_s(radix)` This idea was inspired by @schneems's talk at RubyConf Thailand, where he showed significant overhead in ActiveRecord from Symbol#to_s allocation. -- https://bugs.ruby-lang.org/ Unsubscribe: