Skip to content

Commit

Permalink
Optimize key type check in json_object_i
Browse files Browse the repository at this point in the history
Rather than checking the class we can check the type.
This is very subtly different for String subclasses, but I think it's
OK.

We also save on checking the type again in the fast path.
  • Loading branch information
byroot committed Sep 3, 2024
1 parent 572aa64 commit 772a020
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions ext/json/ext/generator/generator.c
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,6 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
long delim2_len = FBUFFER_LEN(state->object_delim2);
long depth = state->depth;
int j;
VALUE klass, key_to_s;

if (arg->iter > 0) fbuffer_append(buffer, delim, delim_len);
if (object_nl) {
Expand All @@ -859,15 +858,19 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
}
}

klass = CLASS_OF(key);
if (klass == rb_cString) {
key_to_s = key;
} else if (klass == rb_cSymbol) {
key_to_s = rb_sym2str(key);
} else {
key_to_s = rb_funcall(key, i_to_s, 0);
VALUE key_to_s;
switch(rb_type(key)) {
case T_STRING:
key_to_s = key;
break;
case T_SYMBOL:
key_to_s = rb_sym2str(key);
break;
default:
key_to_s = rb_convert_type(key, T_STRING, "String", "to_s");
break;
}
Check_Type(key_to_s, T_STRING);

generate_json(buffer, Vstate, state, key_to_s);
fbuffer_append(buffer, delim2, delim2_len);
generate_json(buffer, Vstate, state, val);
Expand Down

0 comments on commit 772a020

Please sign in to comment.