Skip to content

Commit cea7cae

Browse files
authored
Merge pull request rails#55726 from etiennebarrie/json-no-escape-performance
Add fast-path for Object#to_json(escape: false)
2 parents fe71d6d + 7898364 commit cea7cae

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

activesupport/lib/active_support/json/encoding.rb

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ class << self
4646
def encode(value, options = nil)
4747
if options.nil? || options.empty?
4848
Encoding.encode_without_options(value)
49+
elsif options == { escape: false }.freeze
50+
Encoding.encode_without_escape(value)
4951
else
5052
Encoding.json_encoder.new(options).encode(value)
5153
end
@@ -164,7 +166,14 @@ class JSONGemCoderEncoder # :nodoc:
164166

165167

166168
def initialize(options = nil)
167-
@options = options ? options.dup.freeze : {}.freeze
169+
if options
170+
options = options.dup
171+
@escape = options.delete(:escape) { true }
172+
@options = options.freeze
173+
else
174+
@escape = true
175+
@options = {}.freeze
176+
end
168177
end
169178

170179
# Encode the given object into a JSON string
@@ -173,7 +182,7 @@ def encode(value)
173182

174183
json = CODER.dump(value)
175184

176-
return json unless @options.fetch(:escape, true)
185+
return json unless @escape
177186

178187
# Rails does more escaping than the JSON gem natively does (we
179188
# escape \u2028 and \u2029 and optionally >, <, & to work around
@@ -209,11 +218,16 @@ class << self
209218
def json_encoder=(encoder)
210219
@json_encoder = encoder
211220
@encoder_without_options = encoder.new
221+
@encoder_without_escape = encoder.new(escape: false)
212222
end
213223

214224
def encode_without_options(value) # :nodoc:
215225
@encoder_without_options.encode(value)
216226
end
227+
228+
def encode_without_escape(value) # :nodoc:
229+
@encoder_without_escape.encode(value)
230+
end
217231
end
218232

219233
self.use_standard_json_time_format = true

0 commit comments

Comments
 (0)