diff options
author | Watson <watson1978@gmail.com> | 2018-03-03 01:16:34 +0900 |
---|---|---|
committer | Nobuyoshi Nakada <nobu@ruby-lang.org> | 2019-10-14 19:54:48 +0900 |
commit | d7fa7e2c860430a3dfa1b08be96734925b6c81d8 (patch) | |
tree | b2b1ce9e6c4ba57efd470fc1a84baddf1395bbd2 /ext/json/generator | |
parent | 40724d7d10e9902fcdc4149326acbfe4dd95d3c7 (diff) | |
download | ruby-d7fa7e2c860430a3dfa1b08be96734925b6c81d8.tar.gz |
[flori/json] 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
```
https://github.com/flori/json/commit/c34d01ff6a
Diffstat (limited to 'ext/json/generator')
-rw-r--r-- | ext/json/generator/generator.c | 4 |
1 files changed, 3 insertions, 1 deletions
diff --git a/ext/json/generator/generator.c b/ext/json/generator/generator.c index e8b1476e31..d98879c60d 100644 --- a/ext/json/generator/generator.c +++ b/ext/json/generator/generator.c @@ -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); |