Universal truths

The fact that channel communications (whatever their implementation details) take much, much longer than function calls seems to be a constant truth no matter what the programming language.  I don’t have the benchmarks for Erlang offhand, but here are ones that I just recently ran for Go:

main.BenchmarkChannel-2            500000               6106 ns/op
main.BenchmarkFunction-2        100000000               10.2 ns/op
main.BenchmarkAnonymous-2       100000000               11.5 ns/op

Here’s the source code in case you want to pick holes in my benchmark:

package main

import "testing"

func BenchmarkChannel(b *testing.B) {
        c := make(chan int, 1000)
        accum := 0
        go func() { for { accum += <-c } }()
        for i := 0; i < b.N; i++ {
                c <- i
        }
}

func BenchmarkFunction(b *testing.B) {
        accum := 0
        for i := 0; i < b.N; i++ {
                handle(i, &accum)
        }
}

func handle(v int, accum *int) {
        *accum += v
}

func BenchmarkAnonymous(b *testing.B) {
        accum := 0
        f := func(i int) { accum += i }
        for i := 0; i < b.N; i++ {
                f(i)
        }
}

This was run with:

gotest -run -cpu=2 -bench='.*'

Changing GOMAXPROCS didn’t make any difference. I was running it on a Core 2 Duo.  It’s not hugely surprising, but still.  It makes me wonder how the ratio of performance compares between languages.