Golang 中三種讀取檔案發放效能對比

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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

  以上代碼運行結果列印如下:

123 2017/05/11 19:23:46 read common cost time 25.584882ms2017/05/11 19:23:46 read bufio  cost time 11.857878ms2017/05/11 19:23:46 read ioutil cost time 35.033003ms

  再運行一次列印的結果如下:

123 2017/05/11 21:59:11 read common cost time 32.374922ms2017/05/11 21:59:11 read bufio  cost time 12.155643ms2017/05/11 21:59:11 read ioutil cost time 27.193033ms

   再多運行幾次,發現 readCommon 和 readIOUtil 已耗用時間相差不大,通過查看原始碼發現 io/ioutil 包其實就是封裝了 io 包中的方法,故他們兩沒有效能優先之說;但是不管你運行多少次,readBufio 耗費時間是他們兩各自所耗費時間一半左右。

  由此可見度能最好的是通過帶有緩衝的 io 流來讀取檔案效能最佳。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.