Skip to content

Instantly share code, notes, and snippets.

@nirui
Last active November 24, 2020 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirui/7ecd4e436c5148415c15a5b7805c087a to your computer and use it in GitHub Desktop.
Save nirui/7ecd4e436c5148415c15a5b7805c087a to your computer and use it in GitHub Desktop.
package main
import "testing"
import "sync"
type obj struct {
test string
}
type obj2 struct {
dummy int
test string
}
var testString = "Test String"
func BenchmarkSendFunc(b *testing.B) {
wg := sync.WaitGroup{}
defer wg.Wait()
send := make(chan func() int, 1)
result := make(chan int)
wg.Add(1)
go func(wg *sync.WaitGroup, receive chan func() int) {
defer wg.Done()
total := 0
defer func() {
result <- total
}()
for c := range send {
total += c()
}
}(&wg, send)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if i%2 == 0 {
newObj := obj{test: testString}
send <- func() int {
return len(newObj.test)
}
} else {
newObj := obj2{dummy: 1, test: testString}
send <- func() int {
return len(newObj.test)
}
}
}
close(send)
expectedLen := b.N * len(testString)
if expectedLen != <-result {
b.Error("Result mismatched")
}
}
func BenchmarkSendObj(b *testing.B) {
wg := sync.WaitGroup{}
defer wg.Wait()
send := make(chan obj, 1)
result := make(chan int)
wg.Add(1)
go func(wg *sync.WaitGroup, receive chan obj) {
defer wg.Done()
total := 0
defer func() {
result <- total
}()
for c := range send {
total += len(c.test)
}
}(&wg, send)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
send <- obj{test: testString}
}
close(send)
expectedLen := b.N * len(testString)
if expectedLen != <-result {
b.Error("Result mismatched")
}
}
func BenchmarkSendObjTypeAssert(b *testing.B) {
wg := sync.WaitGroup{}
defer wg.Wait()
send := make(chan interface{}, 1)
result := make(chan int)
wg.Add(1)
go func(wg *sync.WaitGroup, receive chan interface{}) {
defer wg.Done()
total := 0
defer func() {
result <- total
}()
for c := range send {
switch cc := c.(type) {
case obj:
total += len(cc.test)
case obj2:
total += len(cc.test)
default:
panic("Unsupported type")
}
}
}(&wg, send)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if i%2 == 0 {
send <- obj{test: testString}
} else {
send <- obj2{dummy: 1, test: testString}
}
}
close(send)
expectedLen := b.N * len(testString)
if expectedLen != <-result {
b.Error("Result mismatched")
}
}
@nirui
Copy link
Author

nirui commented Nov 24, 2020

$ go test -bench . -benchtime 20s
goos: linux
goarch: amd64
BenchmarkSendFunc-2            	39275546	       627 ns/op	      32 B/op	       1 allocs/op
BenchmarkSendObj-2             	48919554	       452 ns/op	       0 B/op	       0 allocs/op
BenchmarkSendObjTypeAssert-2   	38451140	       624 ns/op	      24 B/op	       1 allocs/op
PASS

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