Skip to content

Commit 91f4a64

Browse files
author
Rob Figueiredo
committed
(*Stream).Flush: reset buffer to beginning
Previously it would append to the end of the buffer instead of reusing the now-free space. Benchmark demonstrates the improvement, run with -benchtime=10s benchmark old ns/op new ns/op delta Benchmark_encode_string_with_SetEscapeHTML-8 447 442 -1.12% Benchmark_jsoniter_large_file-8 20998 21222 +1.07% Benchmark_json_large_file-8 39593 40187 +1.50% Benchmark_stream_encode_big_object-8 10787 8611 -20.17% benchmark old allocs new allocs delta Benchmark_encode_string_with_SetEscapeHTML-8 6 6 +0.00% Benchmark_jsoniter_large_file-8 78 78 +0.00% Benchmark_json_large_file-8 13 13 +0.00% Benchmark_stream_encode_big_object-8 31 0 -100.00% benchmark old bytes new bytes delta Benchmark_encode_string_with_SetEscapeHTML-8 760 760 +0.00% Benchmark_jsoniter_large_file-8 4920 4920 +0.00% Benchmark_json_large_file-8 6640 6640 +0.00% Benchmark_stream_encode_big_object-8 10056 0 -100.00% Fixes #438
1 parent a54d350 commit 91f4a64

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

stream.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -103,14 +103,14 @@ func (stream *Stream) Flush() error {
103103
if stream.Error != nil {
104104
return stream.Error
105105
}
106-
n, err := stream.out.Write(stream.buf)
106+
_, err := stream.out.Write(stream.buf)
107107
if err != nil {
108108
if stream.Error == nil {
109109
stream.Error = err
110110
}
111111
return err
112112
}
113-
stream.buf = stream.buf[n:]
113+
stream.buf = stream.buf[:0]
114114
return nil
115115
}
116116

stream_test.go

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
package jsoniter
22

33
import (
4-
"github.com/stretchr/testify/require"
54
"testing"
5+
6+
"github.com/stretchr/testify/require"
67
)
78

89
func Test_writeByte_should_grow_buffer(t *testing.T) {
@@ -65,5 +66,10 @@ func Test_flush_buffer_should_stop_grow_buffer(t *testing.T) {
6566
writer := new(NopWriter)
6667
NewEncoder(writer).Encode(make([]int, 10000000))
6768
should := require.New(t)
68-
should.Equal(8, writer.bufferSize)
69+
70+
// 512 is the internal buffer size set in NewEncoder
71+
//
72+
// Flush is called after each array element, so only the first 8 bytes of it
73+
// is ever used, and it is never extended. Capacity remains 512.
74+
should.Equal(512, writer.bufferSize)
6975
}

0 commit comments

Comments
 (0)