From 9479a3674892b62c5f483f0aca9f6f83842b69f2 Mon Sep 17 00:00:00 2001 From: Raul Date: Mon, 6 Oct 2025 22:25:34 +0300 Subject: [PATCH 1/2] Optimize tokens objects allocation --- flate/stateless.go | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/flate/stateless.go b/flate/stateless.go index 90b74f7ac..fd25ae35e 100644 --- a/flate/stateless.go +++ b/flate/stateless.go @@ -61,13 +61,19 @@ var bitWriterPool = sync.Pool{ }, } +// tokensPool contains tokens struct objects that can be reused +var tokensPool = sync.Pool{ + New: func() interface{} { + return &tokens{} + }, +} + // StatelessDeflate allows compressing directly to a Writer without retaining state. // When returning everything will be flushed. // Up to 8KB of an optional dictionary can be given which is presumed to precede the block. // Longer dictionaries will be truncated and will still produce valid output. // Sending nil dictionary is perfectly fine. func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { - var dst tokens bw := bitWriterPool.Get().(*huffmanBitWriter) bw.reset(out) defer func() { @@ -91,6 +97,12 @@ func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { // For subsequent loops, keep shallow dict reference to avoid alloc+copy. var inDict []byte + dst := tokensPool.Get().(*tokens) + dst.Reset() + defer func() { + tokensPool.Put(dst) + }() + for len(in) > 0 { todo := in if len(inDict) > 0 { @@ -113,9 +125,9 @@ func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { } // Compress if len(inDict) == 0 { - statelessEnc(&dst, todo, int16(len(dict))) + statelessEnc(dst, todo, int16(len(dict))) } else { - statelessEnc(&dst, inDict[:maxStatelessDict+len(todo)], maxStatelessDict) + statelessEnc(dst, inDict[:maxStatelessDict+len(todo)], maxStatelessDict) } isEof := eof && len(in) == 0 @@ -129,7 +141,7 @@ func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { // If we removed less than 1/16th, huffman compress the block. bw.writeBlockHuff(isEof, uncompressed, len(in) == 0) } else { - bw.writeBlockDynamic(&dst, isEof, uncompressed, len(in) == 0) + bw.writeBlockDynamic(dst, isEof, uncompressed, len(in) == 0) } if len(in) > 0 { // Retain a dict if we have more From f9a02fbf9d95526e3c100693e802c34e8923d608 Mon Sep 17 00:00:00 2001 From: Raul Date: Mon, 6 Oct 2025 22:47:32 +0300 Subject: [PATCH 2/2] . --- flate/stateless.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flate/stateless.go b/flate/stateless.go index fd25ae35e..455ed3e2b 100644 --- a/flate/stateless.go +++ b/flate/stateless.go @@ -63,7 +63,7 @@ var bitWriterPool = sync.Pool{ // tokensPool contains tokens struct objects that can be reused var tokensPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &tokens{} }, }