Skip to content

Commit

Permalink
Unsafe cast to string
Browse files Browse the repository at this point in the history
Avoid the allocation of converting the byte slice or buffer contents to a
string with an unsafe cast. This should be safe because the CheckedEntry is
invalidated once ce.Write is called, so it's not expected to use the
associated string again.

```
name             old time/op    new time/op    delta
Writer/single-4     422ns ±21%     329ns ± 2%   -21.99%  (p=0.000 n=10+10)
Writer/splits-4     433ns ± 4%     384ns ± 5%   -11.26%  (p=0.000 n=9+9)

name             old alloc/op   new alloc/op   delta
Writer/single-4     16.0B ± 0%      0.0B       -100.00%  (p=0.000 n=10+10)
Writer/splits-4     16.0B ± 0%      0.0B       -100.00%  (p=0.000 n=10+10)

name             old allocs/op  new allocs/op  delta
Writer/single-4      2.00 ± 0%      0.00       -100.00%  (p=0.000 n=10+10)
Writer/splits-4      2.00 ± 0%      0.00       -100.00%  (p=0.000 n=10+10)
```
  • Loading branch information
abhinav committed Jun 24, 2021
1 parent 0c8d989 commit 0378e32
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion zapio/writer.go
Expand Up @@ -23,6 +23,7 @@ package zapio
import (
"bytes"
"io"
"unsafe"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
Expand Down Expand Up @@ -114,7 +115,10 @@ func (w *Writer) flush(allowEmpty bool) {
}

func (w *Writer) log(b []byte) {
if ce := w.Log.Check(w.Level, string(b)); ce != nil {
// This is unsafe, but the contract is that a CheckedEntry is no longer
// valid once we call ce.Write, so it promises not to reuse this
// string.
if ce := w.Log.Check(w.Level, *(*string)(unsafe.Pointer(&b))); ce != nil {
ce.Write()
}
}

0 comments on commit 0378e32

Please sign in to comment.