对于 julia 中的文件 io,read()、readline() 或 readlines() 哪个更快?

Which is faster read(), or readline() or readlines() with respect file io in julia?

如有错误请指正:

read 是有效的,正如我假设的那样:

a) read 一次性将整个文件内容读取到内存中,类似于 python.

b) readlinereadlines 一次记一行。

为了扩展评论,这里提供了一些示例基准(另外向您展示了如何自己执行此类测试)。

首先创建一些随机测试数据:

open("testdata.txt", "w") do f
    for i in 1:10^6
        println(f, "a"^100)
    end
end

我们希望以四种方式读入数据(并计算行的总长度):

f1() = sum(length(l) for l in readlines("testdata.txt"))

f2() = sum(length(l) for l in eachline("testdata.txt"))

function f3()
    s = 0
    open("testdata.txt") do f
        while !eof(f)
            s += length(readline(f))
        end
    end
    s
end

function f4()
    s = 0
    for c in read("testdata.txt", String)
        s += c != '\n' # assume Linux for simplicity
    end
    s
end

现在我们比较给定选项的性能和内存使用情况:

julia> using BenchmarkTools

julia> @btime f1()
  239.857 ms (2001558 allocations: 146.59 MiB)
100000000

julia> @btime f2()
  179.480 ms (2001539 allocations: 137.59 MiB)
100000000

julia> @btime f3()
  189.643 ms (2001533 allocations: 137.59 MiB)
100000000

julia> @btime f4()
  158.055 ms (13 allocations: 96.32 MiB)
100000000

如果你 运行 它在你的机器上你应该得到类似的结果。