From e764a6e638b8a9e31df6d929c071c5a289441735 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Mon, 22 Jun 2015 19:40:12 +0200 Subject: [PATCH] Use pooled buffer in replaceShortcodes Even as a copy at the end is needed, this consumes way less memory on Go 1.4.2: ```benchmark old ns/op new ns/op delta BenchmarkParsePage 145979 139964 -4.12% BenchmarkReplaceShortcodeTokens 633574 631946 -0.26% BenchmarkShortcodeLexer 195842 187938 -4.04% benchmark old allocs new allocs delta BenchmarkParsePage 87 87 +0.00% BenchmarkReplaceShortcodeTokens 9424 9415 -0.10% BenchmarkShortcodeLexer 274 274 +0.00% benchmark old bytes new bytes delta BenchmarkParsePage 141830 141830 +0.00% BenchmarkReplaceShortcodeTokens 35219 25385 -27.92% BenchmarkShortcodeLexer 30178 30177 -0.00% ``` See #1148 --- hugolib/shortcode.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/hugolib/shortcode.go b/hugolib/shortcode.go index 630d17daf..ac1a7f1d3 100644 --- a/hugolib/shortcode.go +++ b/hugolib/shortcode.go @@ -458,7 +458,8 @@ func replaceShortcodeTokens(source []byte, prefix string, replacements map[strin return source, nil } - var buff bytes.Buffer + buff := bp.GetBuffer() + defer bp.PutBuffer(buff) sourceLen := len(source) start := 0 @@ -507,7 +508,11 @@ func replaceShortcodeTokens(source []byte, prefix string, replacements map[strin if err != nil { return nil, errors.New("buff write failed") } - return buff.Bytes(), nil + + bc := make([]byte, buff.Len(), buff.Len()) + copy(bc, buff.Bytes()) + + return bc, nil } func getShortcodeTemplate(name string, t tpl.Template) *template.Template {