Skip to content

Commit 38c0f6d

Browse files
Watson1978flori
authored andcommitted
Add shortcut converting to String
In where to convert Hash key to String for json, this patch will add shortcut for String/Symbol in Hash key. ``` $ ruby bench_json_generate.rb Warming up -------------------------------------- json 65.000 i/100ms Calculating ------------------------------------- json 659.576 (± 1.5%) i/s - 3.315k in 5.027127s ``` ``` $ ruby bench_json_generate.rb Warming up -------------------------------------- json 78.000 i/100ms Calculating ------------------------------------- json 789.781 (± 2.7%) i/s - 3.978k in 5.041043s ``` ``` require 'json' require 'benchmark/ips' obj = [] 1000.times do |i| obj << { "id" => i, :age => 42, } end Benchmark.ips do |x| x.report "json" do |iter| count = 0 while count < iter JSON.generate(obj) count += 1 end end end ```
1 parent a73323d commit 38c0f6d

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

ext/json/ext/generator/generator.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -740,7 +740,7 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
740740
long delim2_len = FBUFFER_LEN(state->object_delim2);
741741
long depth = state->depth;
742742
int j;
743-
VALUE key_to_s;
743+
VALUE klass, key_to_s;
744744

745745
if (arg->iter > 0) fbuffer_append(buffer, delim, delim_len);
746746
if (object_nl) {
@@ -752,7 +752,14 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
752752
}
753753
}
754754

755-
key_to_s = rb_funcall(key, i_to_s, 0);
755+
klass = CLASS_OF(key);
756+
if (klass == rb_cString) {
757+
key_to_s = key;
758+
} else if (klass == rb_cSymbol) {
759+
key_to_s = rb_id2str(SYM2ID(key));
760+
} else {
761+
key_to_s = rb_funcall(key, i_to_s, 0);
762+
}
756763
Check_Type(key_to_s, T_STRING);
757764
generate_json(buffer, Vstate, state, key_to_s);
758765
fbuffer_append(buffer, delim2, delim2_len);

0 commit comments

Comments
 (0)