コード
package main
import (
"fmt"
"time"
)
var tests = []string{
"Lorem ipsum dolor sit amet",
"consectetur adipisicing elit",
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua",
"Ut enim ad minim veniam",
"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat",
}
func foo(s string) {
}
func stringSlice() {
for n := 0; n < len(tests); n ++ {
text := tests[n]
for len(text) > 0 {
foo(text[:1])
text = text[1:]
}
}
}
func boo(s []byte) {
}
func byteSlice() {
for n := 0; n < len(tests); n ++ {
text := []byte(tests[n])
for len(text) > 0 {
boo(text[:1])
text = text[1:]
}
}
}
func measure(loop, times int) {
fmt.Println("--- loop:", loop, "---")
var (
start time.Time
end time.Time
)
durations := make([]int64, 2)
for n := 0; n < times; n++ {
start = time.Now()
for n := 0; n < loop; n++ {
stringSlice()
}
end = time.Now()
durations[0] += end.Sub(start).Nanoseconds()
start = time.Now()
for n := 0; n < loop; n++ {
byteSlice()
}
end = time.Now()
durations[1] += end.Sub(start).Nanoseconds()
}
divied := int64(times*1000)
fmt.Println("stringSlice()", durations[0]/divied, "us/times")
fmt.Println("byteSlice()", durations[1]/divied, "us/times")
}
func main() {
measure(100000, 10)
}
結果
loop: 100000
- stringSlice()
- 170,985 us/times
- byteSlice()
- 96,531 us/times
string の slice の方が
1.77
倍時間が掛かってる。
0 件のコメント:
コメントを投稿