From 6274f8a4a0d9aea124dc5abd8ebb139cd6b30c6f Mon Sep 17 00:00:00 2001 From: xiezhengyao Date: Wed, 27 Mar 2024 17:45:19 +0800 Subject: [PATCH] feat: optimize make bytes to reduce memclr cost --- lang/dirtmake/bytes.go | 13 +++++++++++++ lang/dirtmake/bytes_test.go | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 lang/dirtmake/bytes.go create mode 100644 lang/dirtmake/bytes_test.go diff --git a/lang/dirtmake/bytes.go b/lang/dirtmake/bytes.go new file mode 100644 index 00000000..60cc3371 --- /dev/null +++ b/lang/dirtmake/bytes.go @@ -0,0 +1,13 @@ +package dirtmake + +import _ "unsafe" + +//go:linkname rawstring runtime.rawstring +func rawstring(size int) (s string, b []byte) + +// Bytes allocates a byte slice but does not clean up the memory it references. +// NOTE: MUST set any byte element before it's read. +func Bytes(len, cap int) (b []byte) { + _, b = rawstring(cap) + return b[:len] +} diff --git a/lang/dirtmake/bytes_test.go b/lang/dirtmake/bytes_test.go new file mode 100644 index 00000000..ea4aab45 --- /dev/null +++ b/lang/dirtmake/bytes_test.go @@ -0,0 +1,19 @@ +package dirtmake + +import "testing" + +var data []byte + +const testsize = 1024 + +func BenchmarkFastMake(b *testing.B) { + for i := 0; i < b.N; i++ { + data = Bytes(testsize, testsize) + } +} + +func BenchmarkOriginMake(b *testing.B) { + for i := 0; i < b.N; i++ { + data = make([]byte, testsize) + } +}