首先进行循环需要很多时间

时间:2019-02-27 10:56:14

标签: java memory operating-system resources

这是我第二次将这个问题作为第一次被标记为重复的问题,但是这次我没有做任何答复,我对此进行了某些修改。

如今,我正在致力于代码的优化,我看到很多代码,我们在其中创建一个新变量,然后如以下示例代码中的第一个循环所示进行初始化:Code example

BigInteger limit = new BigInteger("10000");
long l = System.currentTimeMillis();
for (BigInteger i = BigInteger.ONE; i.compareTo(limit) < 0; i = 
i.add(BigInteger.ONE))
{
    BigDecimal temp = new BigDecimal(0);
}
long l1 = System.currentTimeMillis();

//After modification
BigDecimal temp1;
for (BigInteger i = BigInteger.ONE; i.compareTo(limit) < 0; i = 
i.add(BigInteger.ONE))
{
    temp1 = new BigDecimal(0);
}
long l2 = System.currentTimeMillis();
System.out.println("1st loop time: "+(l1-l)/1000.0);
System.out.println("2nd loop time: "+(l2-l1)/1000.0);

然后第二步,我做了一些修改,如图所示。我的问题看起来都很熟悉,只是可变范围不同,但是第一个循环需要很多时间。

好的,正如某些人说的那样,使用修改后的代码,但随后我做了另一个实验:Code example

BigInteger limit = new BigInteger("10000");
long l = System.currentTimeMillis();
BigDecimal temp1;
for (BigInteger i = BigInteger.ONE; i.compareTo(limit) < 0; i = i.add(BigInteger.ONE))
{
    temp1 = new BigDecimal(0);
}
long l1 = System.currentTimeMillis();
for (BigInteger i = BigInteger.ONE; i.compareTo(limit) < 0; i = i.add(BigInteger.ONE))
{
    BigDecimal temp = new BigDecimal(0);
}
long l2 = System.currentTimeMillis();
System.out.println("1st loop time: "+(l1-l)/1000.0);
System.out.println("2nd loop time: "+(l2-l1)/1000.0);

在第一个循环中,与第二个循环相比要花费很多时间。但是人们说第一个循环更好,或者有人说第二个循环更好,但是我认为不是。提供一些示例,以便我了解哪个是最好的,以及为什么会发生这种情况。

1 个答案:

答案 0 :(得分:0)

如果您正在考虑代码的时间复杂度
然后,两个循环的复杂度相似,对于内存复杂度,在循环中声明引用变量可能会使用 更多的堆栈内存,编译器可能还会在代码中添加一些优化,这可能是您看到时间差异的原因,也可以在方法上添加volatile修饰符以检查实际性能。volatile将强制编译器不执行此操作方法上的任何优化。