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 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题