输入/输出编码:速度或内存优先级



我目前正在编写一个简单的IO解析,并且对于如何编写它处于两难境地。

这是一个web应用程序的情况,其中这个特定的解析函数可能在一秒钟内被多个用户调用多次。

假设文件大小大于2mb,每次调用的硬件IO延迟为5ms。

第一种情况:内存

第一种情况是为了内存而编码,但以牺牲速度为代价。该函数将占用文件的一小部分,并按这些部分进行解析,从而使用更多的迭代,但使用更少的内存。

伪代码:

function parser() {
    Open file and put into handle variable fHandle
    while (file position not passed EOF) {
        read 1024 bytes from file using fHandle into variable data
        process(data)
    }
    Close file using handle fHandle
}

第二个案例:Speed

第二种情况是为了速度而编码,以牺牲内存使用为代价。该函数将把整个文件内容加载到内存中并直接解析它。

伪代码:

function parser() {
    read entire file and store into variable data
    declare parsing position variable and set to 0
    while (parsing position not past data length) {
        get position of next token and store into variable pos
        process( substring from current position to pos of data )
    }
}

注意:当读取整个文件时,我们使用库的直接可用函数来读取整个文件。在开发人员端读取文件时不使用循环。

第三种情况:最终用户选择

那么是否建议为两者都写,并且每当函数运行时,函数将检测内存是否充足。如果有大量的空闲内存空间,该函数将使用内存密集型版本。

伪代码:

function parser() {
    if (memory is too little) {
        Open file and put into handle variable fHandle
        while (file position not passed EOF) {
            read 1024 bytes from file using fHandle into variable data
            process(data)
        }
        Close file using handle fHandle
    } else {
        read entire file and store into variable data
        declare parsing position variable and set to 0
        while (parsing position not past data length) {
            get position of next token and store into variable pos
            process( substring from current position to pos of data )
        }
    }
}

使用异步I/O(或第二个线程),在驱动器忙于获取下一个数据块时处理一个数据块。两全其美

如果您需要以任何一种方式读取整个文件,并且它适合内存而没有问题,那么从内存中读取它。是每次都是同一个文件,还是一些小文件集?

如果解析的输入通常来自I/O,那么任何好的解析技术(如递归下降)都将受I/O限制。换句话说,从I/O获取字符的平均时间应该超过处理它所花费的平均时间,这是一个健康的因素。所以这并不重要。唯一的区别在于您占用了多少工作存储空间,这通常不是什么大问题。

最新更新