最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Go語(yǔ)言中三種不同md5計(jì)算方式的性能比較

 更新時(shí)間:2017年01月04日 14:57:37   作者:holys''''''''  
md5計(jì)算在我們?nèi)粘9ぷ鞯臅r(shí)候經(jīng)常能遇到,下面這篇文章主要介紹了Go語(yǔ)言中三種不同md5計(jì)算方式的性能比較,需要的朋友可以參考借鑒,下面來一起學(xué)習(xí)學(xué)習(xí)吧。

前言

本文主要介紹的是三種不同的 md5 計(jì)算方式,其實(shí)區(qū)別是讀文件的不同,也就是磁盤 I/O, 所以也可以舉一反三用在網(wǎng)絡(luò) I/O 上。下面來一起看看吧。

ReadFile

先看第一種, 簡(jiǎn)單粗暴:

func md5sum1(file string) string {
 data, err := ioutil.ReadFile(file)
 if err != nil {
 return ""
 }

 return fmt.Sprintf("%x", md5.Sum(data))
}

之所以說其粗暴,是因?yàn)?ReadFile 里面其實(shí)調(diào)用了一個(gè) readall, 分配內(nèi)存是最多的。

Benchmark 來一發(fā):

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

先說明下,這個(gè)文件大小是 19405028 字節(jié),和上面的 19408224 B/op 非常接近, 因?yàn)?readall 確實(shí)是分配了文件大小的內(nèi)存,代碼為證:

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 第二個(gè)參數(shù)是即將創(chuàng)建的 buffer 大小
 return readAll(f, n+bytes.MinRead)
}

func readAll(r io.Reader, capacity int64) (b []byte, err error) {
 // 這個(gè) 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))
}

第二種的特點(diǎn)是:使用了 io.Copy。 在一般情況下(特殊情況在下面會(huì)提到),io.Copy 每次會(huì)分配 32 *1024 字節(jié)的內(nèi)存,即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, 性能相對(duì)要好些。bufio.Reader 默認(rèn)會(huì)創(chuàng)建 4096 字節(jié)的 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 的方式所用內(nèi)存會(huì)比單純的 io.Copy 占用內(nèi)存要少一些呢? 上文也提到, 一般情況下 io.Copy 每次會(huì)分配 32 *1024 字節(jié)的內(nèi)存,那特殊情況是? 答案在源碼中。

一起看看 io.Copy 相關(guān)源碼:

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 這個(gè) Writer 并沒有實(shí)現(xiàn) WriteTo 方法,所以不會(huì)走這里
 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 實(shí)現(xiàn)了 ReadFrom 方法,所以,會(huì)走這里
 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 實(shí)現(xiàn)的 io.Reader 并不會(huì)走默認(rèn)的 buffer創(chuàng)建路徑,而是提前返回了,使用了 bufio.Reader 創(chuàng)建的 buffer, 這也是使用了 bufio.Reader 分配的內(nèi)存會(huì)小一些。

當(dāng)然如果你希望 io.Copy 也分配小一點(diǎn)的內(nèi)存,也是可以做到的,不過是用 io.CopyBuffer, buf 就創(chuàng)建一個(gè) 4096 的 []byte 即可, 就跟 bufio.Reader 區(qū)別不大了。

看看是不是這樣:

// Md5Sum2 用 CopyBufer 重新實(shí)現(xiàn),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

從結(jié)果來看, 分配的內(nèi)存相差不大,畢竟實(shí)現(xiàn)不一樣,不可能一致。

那下次如果你要寫一個(gè)下載大文件的程序,你還會(huì)用 ioutil.ReadAll(resp.Body) 嗎?

最后整體對(duì)比下 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

小結(jié)

這三種不同的 md5 計(jì)算方式在執(zhí)行時(shí)間上都差不多,區(qū)別最大的是內(nèi)存的分配上;

bufio 在處理 I/O 還是很有優(yōu)勢(shì)的,優(yōu)先選擇;

盡量避免 ReadAll 這種用法。

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。

相關(guān)文章

  • 淺談Golang如何使用Viper進(jìn)行配置管理

    淺談Golang如何使用Viper進(jìn)行配置管理

    在Golang生態(tài)中,Viper是一個(gè)不錯(cuò)的開源配置管理框架,這篇文章主要為大家介紹了Golang如何使用Viper進(jìn)行配置管理,需要的可以參考一下
    2023-06-06
  • 使用Go實(shí)現(xiàn)健壯的內(nèi)存型緩存的方法

    使用Go實(shí)現(xiàn)健壯的內(nèi)存型緩存的方法

    這篇文章主要介紹了使用Go實(shí)現(xiàn)健壯的內(nèi)存型緩存,本文比較了字節(jié)緩存和結(jié)構(gòu)體緩存的優(yōu)劣勢(shì),介紹了緩存穿透、緩存錯(cuò)誤、緩存預(yù)熱、緩存?zhèn)鬏?、故障轉(zhuǎn)移、緩存淘汰等問題,并對(duì)一些常見的緩存庫(kù)進(jìn)行了基準(zhǔn)測(cè)試,需要的朋友可以參考下
    2022-05-05
  • 如何將Golang數(shù)組slice轉(zhuǎn)為逗號(hào)分隔的string字符串

    如何將Golang數(shù)組slice轉(zhuǎn)為逗號(hào)分隔的string字符串

    這篇文章主要介紹了如何將Golang數(shù)組slice轉(zhuǎn)為逗號(hào)分隔的string字符串問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • go語(yǔ)言中的Stringer的使用示例詳解

    go語(yǔ)言中的Stringer的使用示例詳解

    Go 語(yǔ)言中的 Stringer 是一個(gè)非常有用的接口,它在標(biāo)準(zhǔn)庫(kù)的 fmt 包中定義,Stringer 接口允許類型定義它們的字符串表示方式,這在格式化輸出時(shí)特別有用,這篇文章主要介紹了go語(yǔ)言中的Stringer的使用,需要的朋友可以參考下
    2025-02-02
  • 詳解Go并發(fā)編程時(shí)如何避免發(fā)生競(jìng)態(tài)條件和數(shù)據(jù)競(jìng)爭(zhēng)

    詳解Go并發(fā)編程時(shí)如何避免發(fā)生競(jìng)態(tài)條件和數(shù)據(jù)競(jìng)爭(zhēng)

    大家都知道,Go是一種支持并發(fā)編程的編程語(yǔ)言,但并發(fā)編程也是比較復(fù)雜和容易出錯(cuò)的。比如本篇分享的問題:競(jìng)態(tài)條件和數(shù)據(jù)競(jìng)爭(zhēng)的問題
    2023-04-04
  • Go 語(yǔ)言 IDE 中的 VSCode 配置使用教程

    Go 語(yǔ)言 IDE 中的 VSCode 配置使用教程

    Gogland 是 JetBrains 公司推出的Go語(yǔ)言集成開發(fā)環(huán)境。這篇文章主要介紹了Go 語(yǔ)言 IDE 中的 VSCode 配置使用教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-05-05
  • go語(yǔ)言通過odbc訪問Sql Server數(shù)據(jù)庫(kù)的方法

    go語(yǔ)言通過odbc訪問Sql Server數(shù)據(jù)庫(kù)的方法

    這篇文章主要介紹了go語(yǔ)言通過odbc訪問Sql Server數(shù)據(jù)庫(kù)的方法,實(shí)例分析了Go語(yǔ)言通過odbc連接與查SQL Server詢數(shù)據(jù)庫(kù)的技巧,需要的朋友可以參考下
    2015-03-03
  • Go語(yǔ)言自定義linter靜態(tài)檢查工具

    Go語(yǔ)言自定義linter靜態(tài)檢查工具

    這篇文章主要介紹了Go語(yǔ)言自定義linter靜態(tài)檢查工具,Go語(yǔ)言是一門編譯型語(yǔ)言,編譯器將高級(jí)語(yǔ)言翻譯成機(jī)器語(yǔ)言,會(huì)先對(duì)源代碼做詞法分析,詞法分析是將字符序列轉(zhuǎn)換為Token序列的過程,文章詳細(xì)介紹需要的小伙伴可以參考一下
    2022-05-05
  • Golang 實(shí)現(xiàn)interface類型轉(zhuǎn)string類型

    Golang 實(shí)現(xiàn)interface類型轉(zhuǎn)string類型

    這篇文章主要介紹了Golang 實(shí)現(xiàn)interface類型轉(zhuǎn)string類型的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • Golang?WorkerPool線程池并發(fā)模式示例詳解

    Golang?WorkerPool線程池并發(fā)模式示例詳解

    這篇文章主要為大家介紹了Golang?WorkerPool線程池并發(fā)模式示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08

最新評(píng)論

枣庄市| 信阳市| 梅州市| 香港 | 宜昌市| 广丰县| 砀山县| 吉林省| 司法| 木里| 华池县| 博湖县| 贵德县| 广西| 渭南市| 乐平市| 仪征市| 读书| 延庆县| 神农架林区| 通辽市| 宣威市| 宣恩县| 邯郸市| 禹城市| 多伦县| 临沭县| 巴中市| 教育| 南康市| 陈巴尔虎旗| 富平县| 固安县| 南通市| 南郑县| 德兴市| 平乐县| 陵川县| 玉林市| 雷山县| 马龙县|