Last active
July 16, 2018 06:43
-
-
Save lysu/39d4e114632d1790af171ed98ab7d8cb to your computer and use it in GitHub Desktop.
cp string
This file contains 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_test | |
import ( | |
"testing" | |
"fmt" | |
) | |
var longStr = "121212123123231231231231311111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111123123" | |
var shortStr = "1212121231232312312311" | |
func BenchmarkLC1(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
longStr = copy1(longStr) | |
} | |
} | |
func BenchmarkLC2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
longStr = copy2(longStr) | |
} | |
} | |
func BenchmarkLC3(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
longStr = copy3(longStr) | |
} | |
} | |
func BenchmarkLC4(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
longStr = copy4(longStr) | |
} | |
} | |
func BenchmarkSC1(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
longStr = copy1(shortStr) | |
} | |
} | |
func BenchmarkSC2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
longStr = copy2(shortStr) | |
} | |
} | |
func BenchmarkSC3(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
longStr = copy3(shortStr) | |
} | |
} | |
func BenchmarkSC4(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
longStr = copy4(shortStr) | |
} | |
} | |
func copy1(s string) string { | |
return fmt.Sprintf("%s", s) | |
} | |
func copy2(s string) string { | |
return string([]byte(s)) | |
} | |
func copy3(a string) string { | |
return (a + " ")[:len(a)] | |
} | |
func copy4(a string) string { | |
if len(a) == 0 { | |
return "" | |
} | |
return a[0:1] + a[1:] | |
} |
func BenchmarkCopyString2(b *testing.B) {
a := "123"
for i := 0; i < b.N; i++ {
a = (a + "")[:len(a)]
}
}
func BenchmarkCopyString3(b *testing.B) {
a := "123"
for i := 0; i < b.N; i++{
a = string(hack.Slice(a))
}
}
func BenchmarkCopyString4(b *testing.B) {
a := "123"
for i:= 0; i< b.N; i ++{
a = string([]byte(a))
}
}
BenchmarkCopyString2-4 100000000 15.9 ns/op 0 B/op 0 allocs/op
BenchmarkCopyString3-4 50000000 42.6 ns/op 3 B/op 1 allocs/op
BenchmarkCopyString4-4 30000000 40.0 ns/op 3 B/op 1 allocs/op
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think we should use
-memprofilerate
: