dongzouqie4220 2017-01-12 08:44
浏览 40
已采纳

代码顺序和性能

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?

  • 写回答

2条回答 默认 最新

  • dongyanfeng0546 2017-01-25 09:01
    关注

    The other answer explained the timing difference, let's get into struct vs. slice.

    If the compiler can figure out at compile time that the slice is big enough, accessing the elements of the slice and a struct will generate identical code. Of course, in reality, often the compiler won't know how big the slice is and completely different optimizations will be applied depending on if you're working with a struct or a slice, so for measuring performance you have to look at a whole program and its behavior, not just one particular operation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog