我想找到哪个更快:struct vs array.所以我编写了一个GO代码,在其中我将4个int值(1,2,3和4)写入结构的成员,然后写入长度为4的数组.我试图找到写入所需的时间.
案例1:首先,我将值写入结构,然后写入数组.在这里,我发现数组比结构更快.
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)
} …Run Code Online (Sandbox Code Playgroud)