亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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ì)算方式的性能比較,需要的朋友可以參考借鑒,下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。

前言

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

ReadFile

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

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

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

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

Benchmark 來(lái)一發(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

先說(shuō)明下,這個(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 并沒(méi)有實(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
}

從上面的源碼來(lái)看, 用 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)存,也是可以做到的,不過(guò)是用 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é)果來(lái)看, 分配的內(nèi)存相差不大,畢竟實(shí)現(xiàn)不一樣,不可能一致。

那下次如果你要寫(xiě)一個(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í)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流。

相關(guān)文章

  • Go語(yǔ)言基礎(chǔ)單元測(cè)試與性能測(cè)試示例詳解

    Go語(yǔ)言基礎(chǔ)單元測(cè)試與性能測(cè)試示例詳解

    這篇文章主要為大家介紹了Go語(yǔ)言基礎(chǔ)單元測(cè)試與性能測(cè)試示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助祝大家多多進(jìn)步
    2021-11-11
  • Golang動(dòng)態(tài)數(shù)組的實(shí)現(xiàn)示例

    Golang動(dòng)態(tài)數(shù)組的實(shí)現(xiàn)示例

    動(dòng)態(tài)數(shù)組能自動(dòng)調(diào)整大小,與靜態(tài)數(shù)組不同,其大小不固定,可根據(jù)需求變化,實(shí)現(xiàn)通常依賴(lài)于數(shù)據(jù)結(jié)構(gòu)如鏈表或數(shù)組加額外信息,本文就來(lái)介紹一下Golang動(dòng)態(tài)數(shù)組的實(shí)現(xiàn)示例,感興趣的可以了解一下
    2024-10-10
  • GO語(yǔ)言基本類(lèi)型分析

    GO語(yǔ)言基本類(lèi)型分析

    這篇文章主要介紹了GO語(yǔ)言基本類(lèi)型,較為詳細(xì)的分析了整形、浮點(diǎn)型、字符串、指針等類(lèi)型的具體用法,是深入學(xué)習(xí)GO語(yǔ)言所必須掌握的重要基礎(chǔ),需要的朋友可以參考下
    2014-12-12
  • go語(yǔ)言channel實(shí)現(xiàn)多核并行化運(yùn)行的方法

    go語(yǔ)言channel實(shí)現(xiàn)多核并行化運(yùn)行的方法

    這篇文章主要介紹了go語(yǔ)言channel實(shí)現(xiàn)多核并行化運(yùn)行的方法,實(shí)例分析了channel實(shí)現(xiàn)多核并行化運(yùn)行的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-03-03
  • Go語(yǔ)言中sync.Mutex的使用方法

    Go語(yǔ)言中sync.Mutex的使用方法

    本文主要介紹了golang中sync.Mutex的實(shí)現(xiàn)方法,mutex主要有兩個(gè) method:Lock()和Unlock(),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • go xorm存庫(kù)處理null值問(wèn)題

    go xorm存庫(kù)處理null值問(wèn)題

    這篇文章主要介紹了go xorm存庫(kù)處理null值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • 詳解Go語(yǔ)言如何對(duì)數(shù)據(jù)庫(kù)進(jìn)行CRUD操作

    詳解Go語(yǔ)言如何對(duì)數(shù)據(jù)庫(kù)進(jìn)行CRUD操作

    在這篇文章中,主要帶大家來(lái)學(xué)習(xí)一下在Go語(yǔ)言中如何對(duì)數(shù)據(jù)庫(kù)進(jìn)行CRUD操作,從而探討一下Go的接口編程,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-05-05
  • Go語(yǔ)言基礎(chǔ)函數(shù)包的使用學(xué)習(xí)

    Go語(yǔ)言基礎(chǔ)函數(shù)包的使用學(xué)習(xí)

    本文通過(guò)一個(gè)實(shí)現(xiàn)加減乘除運(yùn)算的小程序來(lái)介紹go函數(shù)的使用,以及使用函數(shù)的注意事項(xiàng),并引出了對(duì)包的了解和使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • 使用Go重構(gòu)流式日志網(wǎng)關(guān)的實(shí)戰(zhàn)分享

    使用Go重構(gòu)流式日志網(wǎng)關(guān)的實(shí)戰(zhàn)分享

    流式日志網(wǎng)關(guān)的主要功能是提供?HTTP?接口,接收?CDN?邊緣節(jié)點(diǎn)上報(bào)的各類(lèi)日志(訪問(wèn)日志/報(bào)錯(cuò)日志/計(jì)費(fèi)日志等),將日志作預(yù)處理并分流到多個(gè)的?Kafka?集群和?Topic?中,本文就給大家分享如何使用?Go?重構(gòu)流式日志網(wǎng)關(guān)
    2023-06-06
  • Go讀取配置文件的方法總結(jié)

    Go讀取配置文件的方法總結(jié)

    我們常見(jiàn)的配置文件的格式一般有:XML、JSON、INI、YAML、env和.properties,本文小編為大家整理了Go語(yǔ)言讀取這些格式的配置文件的方法,希望對(duì)大家有所幫助
    2023-10-10

最新評(píng)論