我必须在内存中保留数千个字符串,以便在Java中以串行方式访问.我应该将它们存储在数组中还是应该使用某种List?
由于数组将所有数据保存在连续的内存块中(与Lists不同),使用数组存储数千个字符串会导致问题吗?
所以我的理解是增强的for循环应该更慢,因为它们必须使用Iterator.但是我的代码提供了混合结果..(是的我知道循环逻辑占用了循环中花费的大部分时间)
对于较少的迭代次数(100-1000),使用和不使用JIT时,增强的for循环似乎要快得多.相反,迭代次数很多(100000000),传统的循环要快得多.这里发生了什么?
public class NewMain {
public static void main(String[] args) {
System.out.println("Warming up");
int warmup = 1000000;
for (int i = 0; i < warmup; i++) {
runForLoop();
}
for (int i = 0; i < warmup; i++) {
runEnhancedFor();
}
System.out.println("Running");
int iterations = 100000000;
long start = System.nanoTime();
for (int i = 0; i < iterations; i++) {
runForLoop();
}
System.out.println((System.nanoTime() - start) / iterations + "nS");
start = System.nanoTime();
for (int i = 0; i < …Run Code Online (Sandbox Code Playgroud) java ×3
performance ×2
arrays ×1
benchmarking ×1
for-loop ×1
jvm ×1
jvm-hotspot ×1
list ×1
loops ×1