java go md5_Go语言中三种不同md5计算方式的性能比较
前言
本文主要介绍的是三种不同的 md5 计算方式,其实区别是读文件的不同,也就是磁盘 I/O, 所以也可以举一反三用在网络 I/O 上。下面来一起看看吧。
ReadFile
先看第一种, 简单粗暴:
func md5sum1(file string) string {
data, err := ioutil.ReadFile(file)
if err != nil {
return ""
}
return fmt.Sprintf("%x", md5.Sum(data))
}
之所以说其粗暴,是因为 ReadFile 里面其实调用了一个 readall, 分配内存是最多的。
Benchmark 来一发:
var test_path = "/path/to/file"
func BenchmarkMd5Sum1(b *testing.B) {
for i := 0; i < b.N; i++ {
md5sum1(test_path)
}
}
go test -test.run=none -test.bench="^BenchmarkMd5Sum1$" -benchtime=10s -benchmem
BenchmarkMd5Sum1-4 300 43704982 ns/op 19408224 B/op 14 allocs/op
PASS
ok tmp 17.446s
先说明下,这个文件大小是 19405028 字节,和上面的 19408224 B/op 非常接近, 因为 readall 确实是分配了文件大小的内存,代码为证:
ReadFile 源码
// ReadFile reads the file named by filename and returns the contents.
// A successful call returns err == nil, not err == EOF. Because ReadFile
// reads the whole file, it does not treat an EOF from Read as an error
// to be reported.
func ReadFile(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
// It's a good but not certain bet that FileInfo will tell us exactly how much to
// read, so let's try it but be prepared for the answer to be wrong.
var n int64
if fi, err := f.Stat(); err == nil {
// Don't preallocate a huge buffer, just in case.
if size := fi.Size(); size < 1e9 {
n = size
}
}
// As initial capacity for readAll, use n + a little extra in case Size is zero,
// and to avoid another allocation after Read has filled the buffer. The readAll
// call will read into its allocated internal buffer cheaply. If the size was
// wrong, we'll either waste some space off the end or reallocate as needed, but
// in the overwhelmingly common case we'll get it just right.
// readAll 第二个参数是即将创建的 buffer 大小
return readAll(f, n+bytes.MinRead)
}
func readAll(r io.Reader, capacity int64) (b []byte, err error) {
// 这个 buffer 的大小就是 file size + bytes.MinRead
buf := bytes.NewBuffer(make([]byte, 0, capacity))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(r)
return buf.Bytes(), err
}
io.Copy
再看第二种,
func md5sum2(file string) string {
f, err := os.Open(file)
if err != nil {
return ""
}
defer f.Close()
h := md5.New()
_, err = io.Copy(h, f)
if err != nil {
return ""
}
return fmt.Sprintf("%x", h.Sum(nil))
}
第二种的特点是:使用了 io.Copy。 在一般情况下(特殊情况在下面会提到),io.Copy 每次会分配 32 *1024 字节的内存,即32 KB, 然后咱看下 Benchmark 的情况:
func BenchmarkMd5Sum2(b *testing.B) {
for i := 0; i < b.N; i++ {
md5sum2(test_path)
}
}
$ go test -test.run=none -test.bench="^BenchmarkMd5Sum2$" -benchtime=10s -benchmem
BenchmarkMd5Sum2-4 500 37538305 ns/op 33093 B/op 8 allocs/op
PASS
ok tmp 22.657s
32 * 1024 = 32768, 和 上面的 33093 B/op 很接近。
io.Copy + bufio.Reader
然后再看看第三种情况。
这次不仅用了 io.Copy,还用了 bufio.Reader。 bufio 顾名思义, 即 buffered I/O, 性能相对要好些。bufio.Reader 默认会创建 4096 字节的 buffer。
func md5sum3(file string) string {
f, err := os.Open(file)
if err != nil {
return ""
}
defer f.Close()
r := bufio.NewReader(f)
h := md5.New()
_, err = io.Copy(h, r)
if err != nil {
return ""
}
return fmt.Sprintf("%x", h.Sum(nil))
}
看下 Benchmark 的情况:
func BenchmarkMd5Sum3(b *testing.B) {
for i := 0; i < b.N; i++ {
md5sum3(test_path)
}
}
$ go test -test.run=none -test.bench="^BenchmarkMd5Sum3$" -benchtime=10s -benchmem
BenchmarkMd5Sum3-4 300 42589812 ns/op 4507 B/op 9 allocs/op
PASS
ok tmp 16.817s
上面的 4507 B/op 是不是和 4096 很接近? 那为什么io.Copy+ bufio.Reader的方式所用内存会比单纯的 io.Copy占用内存要少一些呢? 上文也提到, 一般情况下 io.Copy 每次会分配 32 *1024 字节的内存,那特殊情况是? 答案在源码中。
一起看看 io.Copy 相关源码:
func Copy(dst Writer, src Reader) (written int64, err error) {
return copyBuffer(dst, src, nil)
}
// copyBuffer is the actual implementation of Copy and CopyBuffer.
// if buf is nil, one is allocated.
func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {
// If the reader has a WriteTo method, use it to do the copy.
// Avoids an allocation and a copy.
// hash.Hash 这个 Writer 并没有实现 WriteTo 方法,所以不会走这里
if wt, ok := src.(WriterTo); ok {
return wt.WriteTo(dst)
}
// Similarly, if the writer has a ReadFrom method, use it to do the copy.
// 而 bufio.Reader 实现了 ReadFrom 方法,所以,会走这里
if rt, ok := dst.(ReaderFrom); ok {
return rt.ReadFrom(src)
}
if buf == nil {
buf = make([]byte, 32*1024)
}
for {
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = ErrShortWrite
break
}
}
if er == EOF {
break
}
if er != nil {
err = er
break
}
}
return written, err
}
从上面的源码来看, 用 bufio.Reader实现的 io.Reader并不会走默认的 buffer创建路径,而是提前返回了,使用了 bufio.Reader创建的 buffer, 这也是使用了 bufio.Reader分配的内存会小一些。
当然如果你希望 io.Copy也分配小一点的内存,也是可以做到的,不过是用 io.CopyBuffer, buf 就创建一个 4096 的 []byte 即可, 就跟 bufio.Reader 区别不大了。
看看是不是这样:
// Md5Sum2 用 CopyBufer 重新实现,buf := make([]byte, 4096)
BenchmarkMd5Sum2-4 500 38484425 ns/op 4409 B/op 8 allocs/op
BenchmarkMd5Sum3-4 500 38671090 ns/op 4505 B/op 9 allocs/op
从结果来看, 分配的内存相差不大,毕竟实现不一样,不可能一致。
那下次如果你要写一个下载大文件的程序,你还会用 ioutil.ReadAll(resp.Body)吗?
最后整体对比下 Benchmark 的情况:
$ go test -test.run=none -test.bench="." -benchtime=10s -benchmem
testing: warning: no tests to run
BenchmarkMd5Sum1-4 300 42551920 ns/op 19408230 B/op 14 allocs/op
BenchmarkMd5Sum2-4 500 38445352 ns/op 33089 B/op 8 allocs/op
BenchmarkMd5Sum3-4 500 38809429 ns/op 4505 B/op 9 allocs/op
PASS
ok tmp 63.821s
小结
这三种不同的 md5 计算方式在执行时间上都差不多,区别最大的是内存的分配上;
bufio 在处理 I/O 还是很有优势的,优先选择;
尽量避免 ReadAll 这种用法。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
java go md5_Go语言中三种不同md5计算方式的性能比较相关推荐
- C语言中三种大括号格式的规范
C语言中三种大括号格式的使用规范 简介: 在C中,使用大括号的方法无所谓对还是错--只要每个开括号后都有一个闭括号,你的程序中就不再会出现与大括号有关的问题.然而,有三种著名的大括号格式:Kernig ...
- zynq学习03 zynq中三种实现GPIO的方式
http://m.blog.csdn.net/article/details?id=52123465 http://blog.chinaaet.com/songhuangong/p/43084 本文介 ...
- Python中三种表示NA的方式
Python中三种表示NA的方式 # -*- coding: utf-8 -*- import numpy as np import pandas as pd# data_frame = np.loa ...
- C语言 scanf三种不同的输入方式
关于C语言 scanf 的三种不同的输入方式 第一种:先输入要读取多少个数,从后面的数字中读取相应个数 代码示意如下 int n,x,flag;scanf("%d",&n) ...
- Java Web开发Tomcat中三种部署项目的方法
第一种方法:在tomcat中的conf目录中,在server.xml中的,<host/>节点中添加: <Context path="/hello" docBas ...
- android项目中有哪几种依赖关系,Android Studio项目中三种依赖的添加方式
通常一个AS项目中的依赖关系有三种,一是本地依赖(主要是对本地的jar包),二是模块依赖,三是远程依赖:添加这些依赖的目的在于上我们想要在项目的某一个模块中使用其中的功能,比如okttp这个网络框架库 ...
- C语言中——三种方法判断是偶数还是奇数
#include <stdio.h> int main(int argc, const char * argv[]) { int a; printf("请输入一个数:" ...
- Spring中三种配置Bean的方式
1.使用xml配置文件 由Spring Framework本身决定,此处不详细说. 2.使用Java注解的配置 如果一个类使用了@Service,那么此类将自动注册成一个bean,不需要再在appli ...
- python 中三种定义类的方式
在Python中方,有三种定义类的方法: 常规方式.@classmethod修饰方式.@staticmethod修饰方式 class类定义 In [1]: class A:...: def commo ...
最新文章
- 【linux】ARM开发板上设置RTC时间,断电重启后,设置失效的原因分析
- 智源发布:悟道 · 文汇 | 面向认知,超大规模新型预训练模型
- C语言中:#define宏的正确使用
- javascript核心_javascript核心之DOM操作
- 9.带有返回值的函数
- .DateTimeToStr函数专用优化版
- 【Java面试题】这道分布式面试题一定要拿下,说说你对CAP的理解?看看高手如何回答
- 八大主流浏览器自动填表功能大比拼
- c语言中isupper用法,C语言中的isupper()函数
- 简述微处理器、微型计算机、微机系统的组成和三者间关系?
- 华为云启动鲲鹏计划,了解更多鲲鹏知识上华为云学院
- CTF必备取证神器(volatility、PTF、取证大师、Magnet AXIOM)
- Android版疯狂填字第三关,iOS/安卓版《疯狂填字3》答案攻略第140关
- crash工具分析sysdump使用
- Beosin(成都链安)预警:黑客攻击EOS竞猜类游戏 已获利数百EOS
- Hyper-V设置多个网口
- FiberSIM 16 v16.0.1
- 合并财务报表及其合并范围的确定
- SEO买卖链接时的注意事项
- linux电脑mac地址修改,linux修改MAC地址/localeLinux -电脑资料
热门文章
- Mysql启动报错解决方案:Failed to open log (file ‘./mysql-bin.000901‘, errno 2)
- 常见的运行时异常与编译时异常举例
- swagger生成错误问题 汇总解决
- IDEA 2019.3新建项目找不到Maven的解决方法
- SVN版本问题:This client is too old to work with working copy 【解决】
- Java:Linux上java -jar xxx.jar命令执行jar包时出现Error: Invalid or corrupt jarfile xxx.jar解决方案
- 80端口被占用时的终极解决方法
- 在Rails资产管道中使用字体
- 系统修复对电脑的影响有哪些
- Frame帧动画帧布局Android