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.
- Is this happening just due to an allocation of memory? Or it's a good approach to declare a variable outside for loop but why?