Golang計算文件MD5

前面這篇文章<Golang裏面MD5的寫法和性能>介紹瞭如何計算字符串的md5,下面我們來說說如何計算文件的md5。

https://wangbjun.site/2020/coding/golang/file-md5.html

1.錯誤的方式

有人說,文件可以讀取成字符串,然後再計算就可以了,如下:

func FileMD5(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
all, err := ioutil.ReadAll(file)
if err != nil {
return "", err
}
return MD5(string(all)), nil
}

此方法確實沒問題,但是需要考慮一個問題,假如文件比較大呢?比如有好幾個GB,如果按這個做法也得佔用好幾個GB內存,肯定存在問題。

經過我測試,在實際運行中,這種方式佔用的內存是文件大小的好幾倍,1個GB的文件需要大概4個GB的內存,太恐怖了。

2.正確的方式

func FileMD5(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
hash := md5.New()
_, _ = io.Copy(hash, file)
return hex.EncodeToString(hash.Sum(nil)), nil
}

經過實際測試發現佔用內存幾乎非常非常少,這裏大家就會發現md5.New()的用途所在了,簡單分析一下爲什麼這種方式佔用內存少。

首先要了解io.Copy方法的含義,可以先看看註釋:

// Copy copies from src to dst until either EOF is reached
// on src or an error occurs. It returns the number of bytes
// copied and the first error encountered while copying, if any.
//
// A successful Copy returns err == nil, not err == EOF.
// Because Copy is defined to read from src until EOF, it does
// not treat an EOF from Read as an error to be reported.
//
// If src implements the WriterTo interface,
// the copy is implemented by calling src.WriteTo(dst).
// Otherwise, if dst implements the ReaderFrom interface,
// the copy is implemented by calling dst.ReadFrom(src).
func Copy(dst Writer, src Reader) (written int64, err error) {
return copyBuffer(dst, src, nil)
}

可以看出來,它底層調用了一個copyBuffer,這個方法底層在copy的時候會臨時分配一個buffer緩存區,默認大小32k,每次只會佔用32k大小內存,如果想自定義緩存區大小可以使用CopyBuffer:

// CopyBuffer is identical to Copy except that it stages through the
// provided buffer (if one is required) rather than allocating a
// temporary one. If buf is nil, one is allocated; otherwise if it has
// zero length, CopyBuffer panics.
func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {
if buf != nil && len(buf) == 0 {
panic("empty buffer in io.CopyBuffer")
}
return copyBuffer(dst, src, buf)
}

最後配合Sum方法,每次計算32k,不斷循環計算,直到算完,所以幾乎不佔用內存。

3.總結

如果計算的文件都是小文件,內存比較大的話,追求速度的話可以使用第一種方法,如果你計算的文件非常大,務必使用第二種方法,不然內存會爆掉。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章