duanlian1320 2017-06-01 07:32
浏览 52
已采纳

在golang中将[] []字节转换为[]字符串的最有效方法

To convert [][]byte to []string, I do this

data, err := ioutil.ReadFile("test.txt")
if err != nil {
    return nil, err
}

db := bytes.Split(data, []uint8("
"))

// Convert [][]byte to []string
s := make([]string, len(db))
for i, val := range db {
    s[i] = string(val)
}
fmt.Printf("%v", s)

I am new to golang, I'm not sure is most efficient way to do this.

  • 写回答

2条回答 默认 最新

  • dongzhankou2090 2017-06-02 10:17
    关注

    If you actually want to convert a file content to a []string, you can use bufio.Scanner which is cleaner (IMO) and more efficient than the code you posted:

    func readFile(filename string) ([]string, error) {
        file, err := os.Open(filename)
        if err != nil {
            return nil, err
        }   
        defer file.Close()
    
        scanner := bufio.NewScanner(file)
    
        var data []string
    
        for scanner.Scan() {
            line := scanner.Text()
            data = append(data, line)
        }   
        if err = scanner.Err(); err != nil {
            return nil, err
        }   
    
        return data, nil 
    }
    

    Here's a benchmark* comparing the original function (readFile1) and my function (readFile2):

    BenchmarkReadFile1-8         300       4632189 ns/op     3035552 B/op      10570 allocs/op
    BenchmarkReadFile2-8        1000       1695820 ns/op     2169655 B/op      10587 allocs/op
    

    *the benchmark read a sample file of 1.2 MiB and ~10K lines

    The new code runs in 36% of the time and 71% of the memory used by the original function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题