# performance - 代碼順序和性能

## go struct (2)

``````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)

}``````

``````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)

}``````

``````package main

import "testing"

type abc struct {
a, b, c, d int
}

func BenchmarkSlice(b *testing.B) {
a := make([]int, 4)
for i := 0; i < b.N; i++ {
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
}
}

func BenchmarkStruct(b *testing.B) {
a := abc{}
for i := 0; i < b.N; i++ {
a.a = 1
a.b = 2
a.c = 3
a.d = 4
}
}``````

``````BenchmarkSlice-4        2000000000           1.24 ns/op
BenchmarkStruct-4       2000000000           0.31 ns/op``````