Last active
August 29, 2015 14:02
-
-
Save taka011239/f60bf285d888df07b1ea to your computer and use it in GitHub Desktop.
Goのclosureへのパラメータの渡し方
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 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" | |
}() | |
} | |
} |
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 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) | |
} | |
} |
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
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