dongzanxun2790 2016-03-19 14:25
浏览 58
已采纳

在使用套接字时重用读取缓冲区

I'd like to know the proper way to reuse the []byte buffer in go. I declare it like this

buf := make([]byte, 1024)

and then use like this

conn, _ := net.Dial("tcp", addr)
_, err = conn.read(buf)

I heard that declaring a new buffer isn't efficient since it involves memory allocations and that we should reuse existing buffers instead. However I am not sure if I just can pass the buffer again and it will be wiped or it can hold parts of previous messages (especially if the current message from socket is shorter than prev.one)?

  • 写回答

3条回答 默认 最新

  • dopuz8728 2016-03-19 15:12
    关注

    In practice you rarely use io.Reader.Read(), instead you pipe it down where io.Reader needed in code. Buffer will not be wiped, you must do it by hand. Or if you want a buffer you can use bufio

    conn, _ := net.Dial("tcp", addr)
    r:=bufio.NewReader(conn)
    

    which you can

    r.WriteTo(io.Writer) //for example for further processing
    

    and you can reset

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度