Skip to content

Commit

Permalink
[flori/json] Convert string encoding to UTF-8 only when needed
Browse files Browse the repository at this point in the history
## 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
```

flori/json@c34d01ff6a
  • Loading branch information
Watson1978 authored and nobu committed Oct 14, 2019
1 parent 40724d7 commit d7fa7e2
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion ext/json/generator/generator.c
Expand Up @@ -810,7 +810,9 @@ static void generate_json_string(FBuffer *buffer, VALUE Vstate, JSON_Generator_S
{
fbuffer_append_char(buffer, '"');
#ifdef HAVE_RUBY_ENCODING_H
obj = rb_str_encode(obj, CEncoding_UTF_8, 0, Qnil);
if (!rb_enc_str_asciicompat_p(obj)) {
obj = rb_str_encode(obj, CEncoding_UTF_8, 0, Qnil);
}
#endif
if (state->ascii_only) {
convert_UTF8_to_JSON_ASCII(buffer, obj);
Expand Down

0 comments on commit d7fa7e2

Please sign in to comment.