简体   繁体   中英

First for loop take much time

Its second time I'm putting this question as the first time it's marked as a duplicate but I didn't get an answer this time I put certain modification in it.

Nowadays I'm working on optimization of code and I see a lot of code in which we create a new variable and then initialize as seen in the first loop in an example code below: 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);

And then in second, I put some modification as shown. My question is both looks familiar, only variable scope is different but the first loop takes much time.

Ok as certain people said use modified code but then I made another experiment like this: 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);

In this first loop is taking much time as compared to the second But people said the first one is better or some said the second one is better but I don't think so. Provide some example so that I can understand which one is best and why it's happening so.

If you are considering time complexity of the code
Then both loops have similar complexity and for memory complexity the declaring reference variable in loop might use More stack memory , also it could happen that compiler adds some optimisation in the code which can be the reason you see difference in time , you can also add volatile modifier on your method to check the actual performance .volatile will force compiler to not to do any optimisation on the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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