我想提交一份500 MB的文件。 我可以加载它,但我想提高性能。 这是缓慢的代码:
File dest = getDestinationFile(source, destination);
if(dest == null) return false;
in = new BufferedInputStream(new FileInputStream(source));
out = new BufferedOutputStream(new FileOutputStream(dest));
byte[] buffer = new byte[1024 * 20];
int i = 0;
// this while loop is very slow
while((i = in.read(buffer)) != -1){
out.write(buffer, 0, i); //<-- SLOW HERE
out.flush();
}
我如何才能找到它为什么慢?
是不是字节数组大小/缓冲大小是否足够? 你有任何想法,以提高性能或?
在此先感谢您的帮助
你不应该在循环冲洗。 您正在使用的BufferedOutputStream。 这意味着,“缓存”的数据一定量后,刷新数据保存到文件。 您的代码只是通过将数据写入的少量冲洗后杀死的数据表现。
尝试做这样的:
while((i = in.read(buffer)) != -1){
out.write(buffer, 0, i); <-- SLOW HERE
}
out.flush();
.. ::编辑:下面::评论的反应..
在我看来,你不应该在所有使用缓冲区。 您正在使用缓冲(输出/输入)流,这意味着他们有自己的缓存数据从磁盘中数据的读取“包”并保存“包”。 我不是100%地肯定表现在使用额外的缓冲,但我希望你告诉我该怎么做:
File dest = getDestinationFile(source, destination);
if(dest == null) return false;
in = new BufferedInputStream(new FileInputStream(source));
out = new BufferedOutputStream(new FileOutputStream(dest));
int i;
while((i = in.read()) != -1){
out.write(i);
}
out.flush();
在我的版本中,你将刚才读一个字节(没有一个INT阅读文档:
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()
该方法返回int,但是这仅仅是一个字节),但没有必要读取整个缓冲区(所以你不必是担心它的大小)。
也许你应该阅读有关流,以便更好地理解什么是与所必要的他们做。