【发布时间】:2012-08-31 17:32:30
【问题描述】:
我正在对 IO 进行一些研究,并阅读了以下有关缓冲技术的文章。为了最大限度地减少底层操作系统的磁盘访问和工作,缓冲技术使用一个临时缓冲区,它以分块方式读取数据,而不是在每次读取操作时直接从磁盘读取数据。
给出了没有缓冲和有缓冲的例子。
没有缓冲:
try
{
File f = new File("Test.txt");
FileInputStream fis = new FileInputStream(f);
int b; int ctr = 0;
while((b = fis.read()) != -1)
{
if((char)b== '\t')
{
ctr++;
}
}
fs.close();
// not the ideal way
} catch(Exception e)
{}
带缓冲:
try
{
File f = new File("Test.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bs = new BufferedInputStream(fis);
int b;
int ctr = 0;
while((b =bs.read()) != -1)
{
if((char)b== '\t')
{
ctr++;
}
}
fs.close(); // not the ideal way
}
catch(Exception e){}
结论是:
Test.txt was a 3.5MB file
Scenario 1 executed between 5200 to 5950 milliseconds for 10 test runs
Scenario 2 executed between 40 to 62 milliseconds for 10 test runs.
在 Java 中还有其他更好的方法吗?或任何其他方法/技术来提供更好的性能?请指教..!
【问题讨论】:
-
代码格式……太可怕了!不,但你能正确缩进代码吗?对于那些想帮助你努力阅读你的代码的人来说,这很烦人。谢谢!