首页 技术 正文
技术 2022年11月15日
0 收藏 679 点赞 4,591 浏览 1617 个字

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

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

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

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

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

package mainimport (
"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, )
for {
readNum, err := file.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if == 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, ) for {
readNum, err := bufReader.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if == 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))
}

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

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

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

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 流来读取文件性能最佳。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294