Skip to content

Commit c34d01f

Browse files
Watson1978flori
authored andcommitted
Convert string encoding to UTF-8 only when needed
## Before ``` $ ruby bench_json_generate.rb Warming up -------------------------------------- json 129.000 i/100ms Calculating ------------------------------------- json 1.300k (± 2.3%) i/s - 6.579k in 5.064656s ``` ## After ``` $ ruby bench_json_generate.rb Warming up -------------------------------------- json 189.000 i/100ms Calculating ------------------------------------- json 1.964k (± 3.3%) i/s - 9.828k in 5.011237s ``` ## Code ``` 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 9ae6d29 commit c34d01f

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

ext/json/ext/generator/generator.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -846,7 +846,9 @@ static void generate_json_string(FBuffer *buffer, VALUE Vstate, JSON_Generator_S
846846
{
847847
fbuffer_append_char(buffer, '"');
848848
#ifdef HAVE_RUBY_ENCODING_H
849-
obj = rb_str_encode(obj, CEncoding_UTF_8, 0, Qnil);
849+
if (!rb_enc_str_asciicompat_p(obj)) {
850+
obj = rb_str_encode(obj, CEncoding_UTF_8, 0, Qnil);
851+
}
850852
#endif
851853
if (state->ascii_only) {
852854
convert_UTF8_to_JSON_ASCII(buffer, obj);

0 commit comments

Comments
 (0)