duanaoshu1989 2019-05-04 17:15
浏览 12
已采纳

在每次循环迭代中重新声明切片是否是错误的做法?

As an example:

for {
    myData := <-myChan
    buf := new(bytes.Buffer)
    encoder := gob.NewEncoder(buf)
    err := encoder.Encode(myData)
    ...

I could put buf := new(... above the for loop to save processor and maybe some memory, but will that cause any problems? Examples I see have the new in the loop.

Edit: for the case above, the encoder could go above the for loop to, so why doesn't it (in examples I've seen)?

  • 写回答

2条回答 默认 最新

  • dongsi3826 2019-05-04 17:21
    关注

    The idiomatic Go style would be to write the clearest code possible as long as it solves the problem at hand within its time and space constraints.

    In other words, I wouldn't worry about the efficiency here because:

    1. The compiler can do clever optimizations that would remove any differences
    2. Almost certainly if there are differences, they are negligible

    If you find out that the allocation takes a considerable portion of each loop iteration, then @peterSO's answer below is a good pattern on how to reuse a bytes.Buffer by calling its Reset method.

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

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器