Given an io.ReadCloser, from the response of an HTTP request for example, what is the most efficient way both in memory overhead and code readability to stream the response to a File?
1条回答 默认 最新
- 普通网友 2015-08-12 02:24关注
io.Copy is undoubtedly the most efficient in terms of code; you only need to
outFile, err := os.Create(filename) // handle err defer outFile.Close() _, err = io.Copy(outFile, res.Body) // handle err
it's also likely to be pretty efficient in terms of CPU and memory as well. You can peek at the implementation of io.Copy if you want; assuming that the body doesn't implement
WriteTo
and the file doesn't implementReadFrom
(a quick glance says that they don't),Copy
will copy chunks of up to 32kB at a time. A bigger chunk would probably use a bit less CPU but more memory; the value they picked seems like a good tradeoff.本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 oracle集群安装出bug
- ¥15 关于#python#的问题:自动化测试
- ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
- ¥15 教务系统账号被盗号如何追溯设备
- ¥20 delta降尺度方法,未来数据怎么降尺度
- ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
- ¥15 再不同版本的系统上,TCP传输速度不一致
- ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
- ¥15 DIFY API Endpoint 问题。
- ¥20 sub地址DHCP问题