Skip to content

Instantly share code, notes, and snippets.

@taka011239
Last active August 29, 2015 14:02
Show Gist options
  • Save taka011239/f60bf285d888df07b1ea to your computer and use it in GitHub Desktop.
Save taka011239/f60bf285d888df07b1ea to your computer and use it in GitHub Desktop.
Goのclosureへのパラメータの渡し方
package closure
type Request struct {
Url string
}
func Closure1(reqs []*Request) {
for _, req := range reqs {
go func(req *Request) {
req.Url = "http://example.org"
}(req)
}
}
func Closure2(reqs []*Request) {
for _, req := range reqs {
req := req
go func() {
req.Url = "http://example.org"
}()
}
}
package closure
import (
"testing"
)
func testHelper() []*Request {
reqs := make([]*Request, 10000)
for i := 0; i < len(reqs); i++ {
reqs[i] = &Request{}
}
return reqs
}
func BenchmarkClosure1(b *testing.B) {
reqs := testHelper()
b.ResetTimer()
for i := 0; i < b.N; i++ {
Closure1(reqs)
}
}
func BenchmarkClosure2(b *testing.B) {
reqs := testHelper()
b.ResetTimer()
for i := 0; i < b.N; i++ {
Closure2(reqs)
}
}
BenchmarkClosure1 500 5356625 ns/op 11165 B/op 38 allocs/op
BenchmarkClosure2 500 6917004 ns/op 262473 B/op 20029 allocs/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment