1

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?
Ammar Ali
  • 692
  • 6
  • 20
  • 1
    This has less to do with the variable declaration, but more with JIT to step in in order to improve runtime execution. – Tom Feb 25 '19 at 09:06
  • As the stack is faster than heap so you are saying JIT will allocating heap for first loop variable and stack for second loop variable. – Ammar Ali Feb 25 '19 at 09:42
  • No, I'm saying that JIT can for example learn that it makes not sense to even create that many `BigDecimal` instances, since they aren't use, so it could remove the instantiation, or replace it with `BigDecimal.ZERO`. Where you declare the variable (inside or outside a code block) doesn't matter that much for performance. – Tom Feb 25 '19 at 09:57
  • Can you please show results of both loops? as i am getting minor difference only. – Muhammad Waqas Feb 25 '19 at 10:06
  • I love it when questions are marked as "duplicate" when the alleged preexisting duplicates do not answer the question. I'm not a Java person so I don't know the answer to the question but I was hoping to learn. – user3344003 Feb 25 '19 at 23:18

0 Answers0