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

时间:2011-12-04 02:44:43

标签: performance memory coding-style io

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

这是Web应用程序的情况,其中该特定解析函数可以在几秒内被多个用户多次调用。

假设文件大小超过2 MB,每次呼叫的硬件IO延迟为5毫秒。

第一种情况:记忆

第一种情况是编码内存,但代价是速度。该函数将接收文件的一小部分并由部分解析,因此使用更多迭代,但内存更少。

的伪代码:

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
}

第二种情况:速度

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

的伪代码:

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 )
        }
    }
}

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果您的解析输入来自I / O,就像通常那样,任何好的解析技术(如递归下降)都将受I / O限制。 换句话说,从I / O获取角色的平均时间应该超过处理它的平均时间,这是一个健康的因素。 所以它真的无关紧要。 唯一的区别在于你的工作存储量是多少,这通常不是什么大问题。