duan0403788996 2016-12-26 07:39
浏览 50
已采纳

Go运行时是否在每次迭代时都评估for循环条件?

Here is a code snippet from the book "The Go Programming Language":

for t := 0.0; t < cycles*2*math.Pi; t += res {
    ...
}

It appears that the expression in the for loop condition t < cycles*2*math.Pi must be evaluated before every iteration of the for loop. Or, does the compiler optimize this by pre-calculating the result of the expression (assuming none of the variables change during the iteration)? Does the above style of coding affect performance?

  • 写回答

3条回答 默认 最新

  • duanfa0072 2016-12-26 08:27
    关注

    This really depends on the Go version but go version go1.7 windows/amd64 does appear to calculate the value once.

    Go code:

    var cycles = 10.0
    var res = 1000.0
    for t := 0.0; t < cycles*2*math.Pi; t += res {
    }
    

    Asm code:

    movsd   [rsp+58h+var_20], xmm0
    mov     [rsp+58h+var_18], 0
    mov     [rsp+58h+var_10], 0
    lea     rax, qword_494500
    mov     [rsp+58h+var_58], rax
    lea     rax, [rsp+58h+var_20]
    mov     [rsp+58h+var_50], rax
    mov     [rsp+58h+var_48], 0
    call    runtime_convT2E
    mov     rax, [rsp+58h+var_40]
    mov     rcx, [rsp+58h+a] ; a
    mov     [rsp+58h+var_18], rax
    mov     [rsp+58h+var_10], rcx
    lea     rax, [rsp+58h+var_18]
    mov     [rsp+58h+var_58], rax
    mov     [rsp+58h+var_50], 1
    mov     [rsp+58h+var_48], 1
    call    fmt_Println
    movsd   xmm0, cs:$f64_408f400000000000
    movsd   xmm1, [rsp+58h+t]
    addsd   xmm0, xmm1
    movsd   [rsp+58h+t], xmm0
    movsd   xmm1, cs:$f64_404f6a7a2955385e
    ucomisd xmm1, xmm0
    ja      loc_401083
    

    f64_404f6a7a2955385e is a precalculated double value equal to 10 * 2 * math.Pi or 62.8318530718

    Go compiler recently switched to SSA, so these kind of optimizations will just keep improving as they greatly benefit from it. For now SSA is only available on amd64:

    Compiler Toolchain

    This release includes a new code generation back end for 64-bit x86 systems, following a proposal from 2015 that has been under development since then. The new back end, based on SSA, generates more compact, more efficient code and provides a better platform for optimizations such as bounds check elimination.

    1.8 should have it for all supported architectures:

    Compiler Toolchain

    Go 1.7 introduced a new compiler back end for 64-bit x86 systems. In Go 1.8, that back end has been developed further and is now used for all architectures.

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

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C