PMD: Avoid instantiating new objects inside loops

22,476

For your specific use case it makes no sense as you keep the reference to the new Object after the loop. So there is no real alternative to your solution.

More generally speaking, creating short lived objects in Java is cheap* (apart from the hidden cost that the GC will run more often). In particular, the allocation is almost free and the time of GC mostly depends on the quantity of reachable objects - dead objects do not increase GC time for typical GC algorithms.

The JIT can also perform various optimisations if it detects that unnecessary objects are created.

Obviously, creating useless is not a recommended practice, but trying to reuse objects is often counterproductive.

As a practical example, you can have a look at this post which shows that creating a new set within a loop is cheaper than creating one before the loop and clearing it at each iteration.

* Thanks @RichardTingle for the link

Share:
22,476
brimborium
Author by

brimborium

Updated on December 06, 2020

Comments

  • brimborium
    brimborium over 3 years

    I've got an issue with the PMD rule Avoid instantiating new objects inside loops. Here is some example code:

    import java.awt.Dimension;
    
    public class PMDDemo {
        public static void main(final String[] args) {
            final Dimension[] arr = new Dimension[10];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = new Dimension(i, i); // rule violation here
            }
        }
    }
    

    PMD gives me the above mentioned rule violation at the marked spot in the code. How am I supposed to create n instances of a class without creating them within a loop?

    I know that some of PMD's rules are controversial (like the onlyOneExit rule). But up to now I at least understood the idea behind them. I don't understand the reasoning behind this rule. Can someone help me with that?