简体   繁体   English

为什么在 java 中的 for 循环中使用 f.length() 效率如此之低?

[英]Why is using f.length() in a for loop so inefficient in java?

I was writing a program that uses some file processing using the file class and a Buffered Input and Output Streams and found that when I used the following code我正在编写一个程序,该程序使用文件 class 和缓冲输入和 Output Streams 使用一些文件处理,发现当我使用以下代码时

for(long j = 0; j < f2.length(); j++) {
    out.write(in.read());
}

was highly inefficient, taking about 15251 milliseconds.效率非常低,大约需要 15251 毫秒。 However if I saved f2.length() to a variable first但是,如果我先将 f2.length() 保存到变量中

long y = f2.length();
for(long j = 0; j < y; j++) {
    out.write(in.read());
}

it only takes 74 milliseconds.它只需要 74 毫秒。 Why is the second block so much more efficient?为什么第二个区块效率更高?

Is it possible that saving f2.length() in a variable y will only compute length() once, and in a for loop it will compute for every iteration, multiplying f2.length() computations n times for n number of iterations.是否有可能将 f2.length() 保存在变量 y 中只会计算一次 length() ,并且在 for 循环中它将计算每次迭代,将 f2.length() 计算乘以 n 次迭代 n 次。

I am curious too.我也很好奇。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM