使用 istringstream 的性能问题

Performance issue using a istringstream

我正在解析一个大型 CSV 文件 (~450 MB)。解析器基于 ifstreamgetline。这非常有效,但需要一些时间。为了减少时间,我尝试将压缩版本的 CSV 文件(~ 21 MB)读入 istringstream 并使用相同的解析器。但是,解析器在使用 ifstream 或 istringstream 时花费相同的时间。根据我的理解,当使用 istringstream 时,解析器应该更快,因为内容已经缓冲在内存中。

这是一些伪代码:

ifstream file(filename)
istream* filePointer = &file
if(gz file) {
    read file into string
    decompress string
    create istringstream from decompressed string
    set filePointer to istringstream
}
parse(filePointer)
---
void parse(istream* file) {
    // ...
    while(getline(*file, line)) {
        // ...
    }
}

性能结果:

这是正常行为吗,istringstream 并不比使用 ifstream 同时读取和解析文件快?

正如您在性能结果中所述,解析时间是恒定的,因此,这两种方法读取文件的速度都比解析文件的速度快。因此速度瓶颈是解析本身,更快地读取文件对性能没有帮助。如果你想进一步优化你的代码,你需要对解析器做一些事情。