Go : buffered channel sum is faster?
On the following playground link,
http://play.golang.org/p/8OAbtn6koN
One method contains buffered channel, and I expected this to perform better because it does not wait for synchronization.
ch := make(chan int, 2)
Three methods that sums an array of random numbers. I benchmark these three functions like the following link:
http://play.golang.org/p/JK3yL4QwOJ
My expection was Buffered channel is Asynchronous and sending or receiving need not wait unless the channel is full, so the buffured channel sum performs better than unbuffered channel sum because it does not take any time to synchronize all goroutines.
[Question 1] So I gave 3 buffer size for buffered channel sum function but the benchmark result is like the following:
Benchmarklinear 10 122170091 ns/op
BenchmarkchSum 20 121921287 ns/op
testing: BenchmarkchSum left GOMAXPROCS set to 4
BenchmarkchSumBuffer 20 118524619 ns/op
testing: BenchmarkchSumBuffer left GOMAXPROCS set to 4
ok ~/Benchmark_sum_01 4.056s
It does not make sense, why in this case the two channel sum perform the same? Should the one with buffer perform better?
[Question 2]
If I give
ch := make(chan int, 1)
I get
Benchmarklinear 10 122170091 ns/op
BenchmarkchSum 20 121921287 ns/op
testing: BenchmarkchSum left GOMAXPROCS set to 4
BenchmarkchSumBuffer 10 118524619 ns/op
testing: BenchmarkchSumBuffer left GOMAXPROCS set to 4
If I give
ch := make(chan int, 2)
I get
Benchmarklinear 10 122170091 ns/op
BenchmarkchSum 10 121921287 ns/op
testing: BenchmarkchSum left GOMAXPROCS set to 4
BenchmarkchSumBuffer 20 118524619 ns/op
testing: BenchmarkchSumBuffer left GOMAXPROCS set to 4
But the result is very inconsistent. Everytime I run the benchmark test, I get a different result.
buffer size does not relate to the performance? Why the benchmark with buffersize 2 gives me different results. With more buffer size, two goroutines never blocks so it seems to take less time.
Thanks in advance.