为什么用golang读写文件比perl慢很多?

问题描述 投票:0回答:0

我正在使用golang来提高代码效率,但是当我使用golang读写文件时,我发现它的读写效率没有Perl高。是我代码的问题还是其他原因?感谢大家的帮助。 构建输入文件:

# Input File:
for i in $(seq 1 600000) do     echo SERVER$((RANDOM%800+100)),$RANDOM,$RANDOM,$RANDOM >> sample.csv done

用Perl读写文件:

time cat sample.csv |perl -ne 'chomp;print"$_"' >out.txt
real    0m0.249s
user    0m0.083s
sys 0m0.049s

使用 Golang 读写文件:

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strings"
)

func main() {

    filepath := "./sample.csv"
    file, err := os.OpenFile(filepath, os.O_RDWR, 0666)
    if err != nil {
        fmt.Println("Open file error!", err)
        return
    }
    defer file.Close()
    buf := bufio.NewReader(file)
    for {
        line, err := buf.ReadString('\n')
        line = strings.TrimSpace(line)
        fmt.Println(line)
        if err != nil {
            if err == io.EOF {
                fmt.Println("File read ok!")
                break
            } else {
                fmt.Println("Read file error!", err)
                return
            }
        }
    }
}

然后我跑:

time go run read.go >out.txt
real    0m2.332s
user    0m0.326s
sys 0m2.038s

为什么golang读写比Perl慢了将近10倍?

go perl bioinformatics
© www.soinside.com 2019 - 2024. All rights reserved.