I wanted to find which is faster: struct vs array. So I wrote a GO code in which I write 4 int values (1,2,3 and 4) to the members of a structure and then to an array of length 4. I tried to find the time it takes to write.
Case1: First, I write values to a structure and then to an array. Here I found array to be faster than structure.
package main
import (
"fmt"
"time"
)
type abc struct {
a, b, c, d int
}
func main() {
var obj abc
t1 := time.Now()
obj.a = 1
obj.b = 2
obj.c = 3
obj.d = 4
t2 := time.Since(t1)
fmt.Println("Struct access time: : ", t2)
a := make([]int, 4)
t3 := time.Now()
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
t4 := time.Since(t3)
fmt.Println("Array access time: : ", t4)
}
Case2: Second, I write values to an array and then a structure. Here I found structure to be faster than array.
package main
import (
"fmt"
"time"
)
type abc struct {
a, b, c, d int
}
func main() {
var obj abc
a := make([]int, 4)
t3 := time.Now()
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
t4 := time.Since(t3)
fmt.Println("Array access time: : ", t4)
t1 := time.Now()
obj.a = 1
obj.b = 2
obj.c = 3
obj.d = 4
t2 := time.Since(t1)
fmt.Println("Struct access time: : ", t2)
}
Why the performance depends on to what I write first? The one that I write to first appears to be slower. Why is it so?