Skip to content

Commit 4329e30

Browse files
mamebyroot
authored andcommitted
Use RB_ENCODING_GET instead of rb_enc_get to improve performance
This speeds up `JSON.generate` by about 12% in a benchmark.
1 parent 6471710 commit 4329e30

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

ext/json/ext/generator/generator.c

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -742,17 +742,19 @@ static void generate_json_array(FBuffer *buffer, VALUE Vstate, JSON_Generator_St
742742
fbuffer_append_char(buffer, ']');
743743
}
744744

745-
static int enc_utf8_compatible_p(rb_encoding *enc)
745+
static int usascii_encindex, utf8_encindex;
746+
747+
static int enc_utf8_compatible_p(int enc_idx)
746748
{
747-
if (enc == rb_usascii_encoding()) return 1;
748-
if (enc == rb_utf8_encoding()) return 1;
749+
if (enc_idx == usascii_encindex) return 1;
750+
if (enc_idx == utf8_encindex) return 1;
749751
return 0;
750752
}
751753

752754
static void generate_json_string(FBuffer *buffer, VALUE Vstate, JSON_Generator_State *state, VALUE obj)
753755
{
754756
fbuffer_append_char(buffer, '"');
755-
if (!enc_utf8_compatible_p(rb_enc_get(obj))) {
757+
if (!enc_utf8_compatible_p(RB_ENCODING_GET(obj))) {
756758
obj = rb_str_export_to_enc(obj, rb_utf8_encoding());
757759
}
758760
convert_UTF8_to_JSON(buffer, obj, state->ascii_only, state->script_safe);
@@ -1479,4 +1481,7 @@ void Init_generator(void)
14791481
i_match = rb_intern("match");
14801482
i_keys = rb_intern("keys");
14811483
i_dup = rb_intern("dup");
1484+
1485+
usascii_encindex = rb_usascii_encindex();
1486+
utf8_encindex = rb_utf8_encindex();
14821487
}

0 commit comments

Comments
 (0)