Skip to content

Commit

Permalink
Use memcpy() to dump true/false/null (#736)
Browse files Browse the repository at this point in the history
Maybe, the standard C library may use SIMD instructions,
so it is faster than our own code.

Similar:
- #734
- #674

−               | before | after  | result
--               | --     | --     | --
Oj.dump (macOS)  | 1.699M | 2.020M | 1.189x
Oj.dump (Linux)  | 1.849M | 2.260M | 1.222x

### Environment
- macOS
  - macOS 12.1
  - Apple M1 Max
  - Apple clang version 13.0.0 (clang-1300.0.29.30)
  - Ruby 3.1.0
- Linux
  - Zorin OS 16
  - AMD Ryzen 7 5700G
  - gcc version 11.1.0
  - Ruby 3.1.0

### macOS
#### Before
```
Warming up --------------------------------------
             Oj.dump   169.730k i/100ms
Calculating -------------------------------------
             Oj.dump      1.699M (± 0.7%) i/s -     25.629M in  15.089624s
```

#### After
```
Warming up --------------------------------------
             Oj.dump   201.206k i/100ms
Calculating -------------------------------------
             Oj.dump      2.020M (± 0.9%) i/s -     30.382M in  15.044372s
```

### Linux
#### Before
```
Warming up --------------------------------------
             Oj.dump   180.943k i/100ms
Calculating -------------------------------------
             Oj.dump      1.849M (± 1.1%) i/s -     27.865M in  15.072276s
```

#### After
```
Warming up --------------------------------------
             Oj.dump   224.695k i/100ms
Calculating -------------------------------------
             Oj.dump      2.260M (± 1.4%) i/s -     33.929M in  15.012352s
```

### Test code
```ruby
require 'benchmark/ips'
require 'oj'

data = {
  true: (0..10).map { true },
  false: (0..10).map { false },
  null: (0..10).map { nil },
}

Benchmark.ips do |x|
  x.time = 15

  x.report('Oj.dump') { Oj.dump(data) }
end
```
  • Loading branch information
Watson1978 committed Jan 14, 2022
1 parent 8bceb9c commit 0301e0f
Showing 1 changed file with 6 additions and 13 deletions.
19 changes: 6 additions & 13 deletions ext/oj/dump.c
Expand Up @@ -981,29 +981,22 @@ void oj_grow_out(Out out, size_t len) {

void oj_dump_nil(VALUE obj, int depth, Out out, bool as_ok) {
assure_size(out, 4);
*out->cur++ = 'n';
*out->cur++ = 'u';
*out->cur++ = 'l';
*out->cur++ = 'l';
memcpy(out->cur, "null", 4);
out->cur += 4;
*out->cur = '\0';
}

void oj_dump_true(VALUE obj, int depth, Out out, bool as_ok) {
assure_size(out, 4);
*out->cur++ = 't';
*out->cur++ = 'r';
*out->cur++ = 'u';
*out->cur++ = 'e';
memcpy(out->cur, "true", 4);
out->cur += 4;
*out->cur = '\0';
}

void oj_dump_false(VALUE obj, int depth, Out out, bool as_ok) {
assure_size(out, 5);
*out->cur++ = 'f';
*out->cur++ = 'a';
*out->cur++ = 'l';
*out->cur++ = 's';
*out->cur++ = 'e';
memcpy(out->cur, "false", 5);
out->cur += 5;
*out->cur = '\0';
}

Expand Down

0 comments on commit 0301e0f

Please sign in to comment.