Skip to content

Commit 4af700e

Browse files
authored
Merge pull request ruby#674 from eregon/faster-checks-for-generate_json
Speedup #generate_json by using case/when/end
2 parents a9bc48e + 82d21f0 commit 4af700e

File tree

2 files changed

+16
-16
lines changed

2 files changed

+16
-16
lines changed

lib/json/pure/generator.rb

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -307,20 +307,18 @@ def generate(obj)
307307

308308
# Handles @allow_nan, @buffer_initial_length, other ivars must be the default value (see above)
309309
private def generate_json(obj, buf)
310-
klass = obj.class
311-
if klass == Hash
310+
case obj
311+
when Hash
312312
buf << '{'
313313
first = true
314314
obj.each_pair do |k,v|
315315
buf << ',' unless first
316316

317317
key_str = k.to_s
318-
if key_str.is_a?(::String)
319-
if key_str.class == ::String
320-
fast_serialize_string(key_str, buf)
321-
else
322-
generate_json(key_str, buf)
323-
end
318+
if key_str.class == String
319+
fast_serialize_string(key_str, buf)
320+
elsif key_str.is_a?(String)
321+
generate_json(key_str, buf)
324322
else
325323
raise TypeError, "#{k.class}#to_s returns an instance of #{key_str.class}, expected a String"
326324
end
@@ -330,7 +328,7 @@ def generate(obj)
330328
first = false
331329
end
332330
buf << '}'
333-
elsif klass == Array
331+
when Array
334332
buf << '['
335333
first = true
336334
obj.each do |e|
@@ -339,9 +337,13 @@ def generate(obj)
339337
first = false
340338
end
341339
buf << ']'
342-
elsif klass == String
343-
fast_serialize_string(obj, buf)
344-
elsif klass == Integer
340+
when String
341+
if obj.class == String
342+
fast_serialize_string(obj, buf)
343+
else
344+
buf << obj.to_json(self)
345+
end
346+
when Integer
345347
buf << obj.to_s
346348
else
347349
# Note: Float is handled this way since Float#to_s is slow anyway
@@ -432,8 +434,8 @@ def json_transform(state)
432434
result << state.indent * depth if indent
433435

434436
key_str = key.to_s
435-
key_json = if key_str.is_a?(::String)
436-
key_str = key_str.to_json(state)
437+
if key_str.is_a?(String)
438+
key_json = key_str.to_json(state)
437439
else
438440
raise TypeError, "#{key.class}#to_s returns an instance of #{key_str.class}, expected a String"
439441
end

test/json/json_parser_test.rb

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,6 @@ def test_argument_encoding_for_binary_unmodified
3232
end
3333

3434
def test_error_message_encoding
35-
pend if RUBY_ENGINE == 'truffleruby'
36-
3735
bug10705 = '[ruby-core:67386] [Bug #10705]'
3836
json = ".\"\xE2\x88\x9A\""
3937
assert_equal(Encoding::UTF_8, json.encoding)

0 commit comments

Comments
 (0)