分享
  1. 首页
  2. 文章

Golang 中三种读取文件发放性能对比

grimm · · 1981 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Golang 中读取文件大概有三种方法,分别为:

1. 通过原生态 io 包中的 read 方法进行读取

2. 通过 io/ioutil 包提供的 read 方法进行读取

3. 通过 bufio 包提供的 read 方法进行读取

下面通过代码来验证这三种方式的读取性能,并总结出我们平时应该使用的方案,以便我们可以写出最优代码:

package main
import (
 "os"
 "io"
 "bufio"
 "io/ioutil"
 "time"
 "log"
)
func readCommon(path string) {
 file, err := os.Open(path)
 if err != nil {
 panic(err)
 }
 defer file.Close()
 buf := make([]byte, 1024)
 for {
 readNum, err := file.Read(buf)
 if err != nil && err != io.EOF {
 panic(err)
 }
 if 0 == readNum {
 break
 }
 }
}
func readBufio(path string) {
 file, err := os.Open(path)
 if err != nil {
 panic(err)
 }
 defer file.Close()
 bufReader := bufio.NewReader(file)
 buf := make([]byte, 1024)
 for {
 readNum, err := bufReader.Read(buf)
 if err != nil && err != io.EOF {
 panic(err)
 }
 if 0 == readNum {
 break
 }
 }
}
func readIOUtil(path string) {
 file, err := os.Open(path)
 if err != nil {
 panic(err)
 }
 defer file.Close()
 _, err = ioutil.ReadAll(file)
}
func main() {
 //size is 26MB
 pathName := "/Users/mfw/Desktop/shakespeare.json"
 start := time.Now()
 readCommon(pathName)
 timeCommon := time.Now()
 log.Printf("read common cost time %v\n", timeCommon.Sub(start))
 readBufio(pathName)
 timeBufio := time.Now()
 log.Printf("read bufio cost time %v\n", timeBufio.Sub(timeCommon))
 readIOUtil(pathName)
 timeIOUtil := time.Now()
 log.Printf("read ioutil cost time %v\n", timeIOUtil.Sub(timeBufio))
}

以上代码运行结果打印如下:

1
2
3
2017年05月11日 19:23:46 read common cost time 25.584882ms
2017年05月11日 19:23:46 read bufio cost time 11.857878ms
2017年05月11日 19:23:46 read ioutil cost time 35.033003ms

再运行一次打印的结果如下:

1
2
3
2017年05月11日 21:59:11 read common cost time 32.374922ms
2017年05月11日 21:59:11 read bufio cost time 12.155643ms
2017年05月11日 21:59:11 read ioutil cost time 27.193033ms

再多运行几次,发现 readCommon 和 readIOUtil 运行时间相差不大,通过查看源代码发现 io/ioutil 包其实就是封装了 io 包中的方法,故他们两没有性能优先之说;但是不管你运行多少次,readBufio 耗费时间是他们两各自所耗费时间一半左右。

由此可见性能最好的是通过带有缓冲的 io 流来读取文件性能最佳。


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:grimm

查看原文:Golang 中三种读取文件发放性能对比

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1981 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏