Last active
October 24, 2024 06:39
-
-
Save teivah/b36f7c329b3e7b2d81cbc067e62931d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
cpu: Apple M1 | |
BenchmarkString1 | |
BenchmarkString1-8 3292 362786 ns/op | |
BenchmarkString2 | |
BenchmarkString2-8 27062 43746 ns/op | |
PASS | |
*/ | |
package foo | |
import ( | |
"fmt" | |
"strconv" | |
"strings" | |
"testing" | |
) | |
func String1(m map[string]string) string { | |
return fmt.Sprintf("%v", m) | |
} | |
func String2(m map[string]string) string { | |
res := make([]string, 0, len(m)) | |
for k, v := range m { | |
res = append(res, k+"="+v) | |
} | |
return strings.Join(res, ",") | |
} | |
var global string | |
func BenchmarkString1(b *testing.B) { | |
m := inputMap() | |
b.ResetTimer() | |
var local string | |
for i := 0; i < b.N; i++ { | |
local = String1(m) | |
} | |
global = local | |
} | |
func BenchmarkString2(b *testing.B) { | |
m := inputMap() | |
b.ResetTimer() | |
var local string | |
for i := 0; i < b.N; i++ { | |
local = String2(m) | |
} | |
global = local | |
} | |
func inputMap() map[string]string { | |
l := 1000 | |
m := make(map[string]string, l) | |
for i := 0; i < l; i++ { | |
v := strings.Repeat("-", 10) | |
m[v+strconv.Itoa(i)] = v | |
} | |
return m | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment