Last active
April 13, 2020 06:03
-
-
Save optix2000/73c9f298672c1c27b6512bf8be67803b to your computer and use it in GitHub Desktop.
goroutine vs channel vs single threading performance
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 | |
import "testing" | |
var channel = make(chan []byte, 1024) | |
var data = make([]byte, 1024) | |
var sink = []byte{} | |
func goroutine(data []byte) { | |
sink = data | |
} | |
func channelroutine(channel <-chan []byte) { | |
for data := range channel { | |
sink = data | |
} | |
} | |
func init() { | |
go channelroutine(channel) | |
} | |
func BenchmarkGoRoutine(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
go goroutine(data) | |
} | |
} | |
func BenchmarkChannel(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
channel <- data | |
} | |
} | |
func BenchmarkNormal(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
sink = data | |
} | |
} |
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
# MacBook Pro (15-inch, 2017) | |
# 10.15.4 (19E287) | |
% go test -bench=. | |
goos: darwin | |
goarch: amd64 | |
pkg: test | |
BenchmarkGoRoutine-8 4393114 271 ns/op | |
BenchmarkChannel-8 13652916 83.2 ns/op | |
BenchmarkNormal-8 1000000000 0.924 ns/op | |
PASS | |
ok test 3.803s | |
go test -bench=. 9.47s user 1.58s system 262% cpu 4.211 total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment