Last active
September 1, 2017 00:41
-
-
Save sgryjp/775c007e92518ed6fb695729e8c79bec to your computer and use it in GitHub Desktop.
Golang: Performance test of string variable copy
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
package main | |
import "testing" | |
import "strings" | |
import "fmt" | |
type StructWithString struct { | |
Str string | |
} | |
func Benchmark_StringCopy(b *testing.B) { | |
strLen := new(int) | |
scanTest := func(b *testing.B) { | |
a := strings.Repeat("a", *strLen) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = strings.Index(a, "!") | |
} | |
} | |
copyStringTest := func(b *testing.B) { | |
x := strings.Repeat("a", *strLen) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = x | |
} | |
} | |
copyStructTest := func(b *testing.B) { | |
x := StructWithString{strings.Repeat("a", *strLen)} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = x | |
} | |
} | |
for i := 1; i < 10; i++ { | |
*strLen = i * 1024 * 1024 | |
b.Run(fmt.Sprintf("%dMB_ScanTest", i), scanTest) | |
b.Run(fmt.Sprintf("%dMB_CopyString", i), copyStringTest) | |
b.Run(fmt.Sprintf("%dMB_CopyStruct", i), copyStructTest) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It seems Go does not copy content (characters inside) of string variables when making a copy of it -- copying is far faster than scanning it (Go should copying the address of the string content, not the content them selves). So, we don't need to worry about performance of copying string variables.
Test result on my laptop: