Skip to content

Instantly share code, notes, and snippets.

@pocke
Created March 17, 2015 23:31
Show Gist options
  • Save pocke/93804909369803174635 to your computer and use it in GitHub Desktop.
Save pocke/93804909369803174635 to your computer and use it in GitHub Desktop.
strconv.AppendIntはやい
package main
import (
"fmt"
"strconv"
"testing"
)
func F1(n int) string {
res := ""
for i := 0; i < n; i++ {
res += fmt.Sprintf("%d yen\n", i)
}
return res
}
func F2(n int) string {
res := make([]byte, 0, n*3+5*n)
for i := 0; i < n; i++ {
res = append(res, fmt.Sprintf("%d yen\n", i)...)
}
return string(res)
}
func F3(n int) string {
res := make([]byte, 0, n*3+5*n)
for i := 0; i < n; i++ {
res = append(res, strconv.Itoa(i)...)
res = append(res, " yen\n"...)
}
return string(res)
}
func F4(n int) string {
res := make([]byte, 0, n*3+5*n)
for i := 0; i < n; i++ {
res = strconv.AppendInt(res, int64(i), 10)
res = append(res, " yen\n"...)
}
return string(res)
}
func TestEq(t *testing.T) {
n := 100
res := F1(n)
if !(res == F2(n) && res == F3(n) && res == F4(n)) {
t.Error("fail")
}
}
func BenchmarkF1(b *testing.B) {
for i := 0; i < b.N; i++ {
F1(100)
}
}
func BenchmarkF2(b *testing.B) {
for i := 0; i < b.N; i++ {
F2(100)
}
}
func BenchmarkF3(b *testing.B) {
for i := 0; i < b.N; i++ {
F3(100)
}
}
func BenchmarkF4(b *testing.B) {
for i := 0; i < b.N; i++ {
F4(100)
}
}
@pocke
Copy link
Author

pocke commented Mar 18, 2015

$ go version
go version go1.4.2 linux/amd64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment