Issue #15895 has been updated by ashmaroli (Ashwin Maroli).


Thank you for pointing me to `CGI.escape_html`. I was not aware of it being faster than the `gsub` route. Moreover, you're right about the `gsub` usage not being a bottleneck in my codebase.

It simply resulted in numerous string allocations (as reported by the `memory_profiler` gem) that I wanted to reduce or eliminate.

As it turns out, `CGI.escape_html` allocates lesser Ruby strings than `gsub`. So, it is a win-win solution for me.

Thank you once again.

----------------------------------------
Bug #15895: String#gsub and String#sub should return original string if no substitution(s) have been made 
https://bugs.ruby-lang.org/issues/15895#change-78314

* Author: ashmaroli (Ashwin Maroli)
* Status: Feedback
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: 2.4.5
* Backport: 2.4: UNKNOWN, 2.5: UNKNOWN, 2.6: UNKNOWN
----------------------------------------
Currently if one were to call `'Hello World'.gsub(/[<&>]/, html_entities_hash)` , a copy of 'Hello World' is allocated and returned. If such a call were to occur inside a loop, then that would cause numerous copies to be allocated simply from an attempt at substitution.

Likewise for `'Hello World'.sub(/\d+/, 'x')`

Opting for the destructive alternatives is not possible since the original string should remain unchanged in all cases.

IMO, it'd be great to have the original string returned if substitution(s) couldn't be made.



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

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>