谁能解释为什么会这样?文件大小最大为 2MB。代码执行时间不到 2 秒。
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
catch(Exception e)
{
}
但是当我将代码更改为:
String temp = "";
try {
while ((line = br.readLine()) != null) {
temp =temp + line;
}
catch(Exception e)
{
}
我知道这会花费相对更多的时间,但需要 470 秒的大量时间。为什么会有这种差异?
最佳答案
temp =temp + line;
按原样连接字符串。串联需要创建一个新的字符串对象,并且可能需要驻留,这会花费很多时间。相反,考虑在大多数情况下使用 StringBuilder 或在需要同步的情况下使用 StringBuffer。
创建一次
StringBuilder sb=new StringBuilder()
并追加:
sb.append(line);
然后您可以使用 sb.toString()
获取数据。
关于java - 文件读取时执行速度差异较大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17575286/