Why for-range behaves differently depending on the size of the element (A peek into go compiler optimization)
It’s all started when my colleague asked this question.
1package main
2
3import "testing"
4
5const size = 1000000
6
7type SomeStruct struct {
8 ID0 int64
9 ID1 int64
10 ID2 int64
11 ID3 int64
12 ID4 int64
13 ID5 int64
14 ID6 int64
15 ID7 int64
16 ID8 int64
17}
18
19func BenchmarkForVar(b *testing.B) {
20 slice := make([]SomeStruct, size)
21 b.ReportAllocs()
22 b.ResetTimer()
23 for i := 0; i < b.N; i++ {
24 for _, s := range slice { // index and value
25 _ = s
26 }
27 }
28}
29func BenchmarkForCounter(b *testing.B) {
30 slice := make([]SomeStruct, size)
31 b.ReportAllocs()
32 b.ResetTimer()
33 for i := 0; i < b.N; i++ {
34 for i := range slice { // only use the index
35 s := slice[i]
36 _ = s
37 }
38 }
39}
Testing go 1.5 cross compilation on raspberry pi
I’m so excited with the new release of golang. One particular feature
is now very easy to build for multiple architecture. If you seen my other posts,
I also like to tinker with my raspberry-pi. On my previous project I use either ruby
or python for building some stuff. One annoying thing is dependency, setup and compilation
is usually quite slow. Would be cool if I could just create some stuff in desktop and just
scp the binary to pi and everything should work!
Stubbing Time.Now() in golang
Sometimes it’s really hard to test functionality that involve with system time.
Especially when we want to test the function with a specific time. For example testing
whether today is end of month or test 2 different behavior at a different time
Below we look into different ways we can mock or stub the time. Each with it’s own
advantages and disadvantages.
Passing the time instance
1func CheckEndOfMonth(now time.Time) {
2 // business process
3}
4
5func main() {
6 CheckEndOfMonth(time.Now())
7}
8
9// for test
10func TestCheckEndOfMonth(t *testing.T) {
11 CheckEndOfMonth(time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC))
12}