Skip to content

memory: Pool of bytes buffers

Pavlo Strokov requested to merge ps-bytes-pool into master

In order to reduce memory allocations and better utilise already allocated memory it makes sense to use a shared pool of *bytes.Buffer instances. The solution uses a standard sync.Pool that is used in stdlib for the same purpose. The Buffer() function acquires a new or existing instance from the pool and a release function that resets content of the buffer and returns it back to the pool.

It also replaces usage of the String() method with Bytes() method as the later doesn't require memory allocation.

func BenchmarkAllocStrings(b *testing.B) {
	buf, release := helper.Buffer()
	defer release()

	buf.WriteString("Hello")
	buf.WriteString(time.Now().String())
	buf.WriteString("Fresh")

	var a = 0
	for i := 0; i < b.N; i++ {
		if strings.HasPrefix(buf.String(), "Hello") {
			a += 1
		}
	}

	print(a)
}

Screenshot_2021-09-23_at_11.24.28

func BenchmarkAllocBytes(b *testing.B) {
	buf, release := helper.Buffer()
	defer release()

	buf.WriteString("Hello")
	buf.WriteString(time.Now().String())
	buf.WriteString("Fresh")

	var a = 0
	for i := 0; i < b.N; i++ {
		if bytes.HasPrefix(buf.Bytes(), []byte("Hello")) {
			a += 1
		}
	}

	print(a)
}

Screenshot_2021-09-23_at_11.24.09

Closes: #3791 (closed)

Merge request reports

Loading