Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Map2Kvs functions by pre-allocating memory #522

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

me-cs
Copy link

@me-cs me-cs commented Sep 23, 2024

goos: windows
goarch: amd64
pkg: github.com/dtm-labs/dtm/client/dtmgrpc/dtmgimp
cpu: Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
BenchmarkMap2Kvs
BenchmarkMap2Kvs-16 61436 19822 ns/op
BenchmarkMap2KvsOld
BenchmarkMap2KvsOld-16 30886 38553 ns/op
PASS

package dtmgimp

import (
	"math/rand"
	"testing"
)

const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

func RandStringBytes(n int) string {
	b := make([]byte, n)
	for i := range b {
		b[i] = letterBytes[rand.Intn(len(letterBytes))]
	}
	return string(b)
}

var m = func() map[string]string {
	m := make(map[string]string)
	for i := 0; i < 1000; i++ {
		m[RandStringBytes(100)] = "exist"
	}
	return m
}()

// Map2Kvs map to metadata kv
func Map2KvsNew(m map[string]string) []string {
	kvs := make([]string, 0, len(m)<<1)
	for k, v := range m {
		kvs = append(kvs, k, v)
	}
	return kvs
}

// Map2Kvs map to metadata kv
func Map2KvsOld(m map[string]string) []string {
	kvs := []string{}
	for k, v := range m {
		kvs = append(kvs, k, v)
	}
	return kvs
}

func BenchmarkMap2Kvs(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_ = Map2KvsNew(m)
	}
}

func BenchmarkMap2KvsOld(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_ = Map2KvsOld(m)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant