24

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?

brimborium
  • 9,362
  • 9
  • 48
  • 76

2 Answers2

28

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

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
-1
for (int i = 0; i < arr.length; i++) {
  arr[i] = new Dimension(i, i); // rule violation here
}

The Above Pmd can be resolved by

 for (int i = 0; i < arr.length; i++) {
   arr[i] = createNewDimension(i,i); // rule violation here
 }

 private static Dimension createNewDimension(i,i) {
   return new Dimension(i, i);
 }

we should not directly use new operator inside a loop just move this inside a private method.

brimborium
  • 9,362
  • 9
  • 48
  • 76
Vishnu Ranganathan
  • 1,277
  • 21
  • 45
  • 3
    Thanks for the input. Would you actually prefer the resolved version (with the creation wrapper)? I think this makes it less readable. But maybe I am missing something. +1 for actually resolving the violation though. – brimborium Dec 05 '16 at 16:32
  • Simply wrapping the creation of the object in a method does not actually prevent instantiation within a loop. It's simply a subversion of the rule's implementation. – Linus Fernandes Jan 10 '20 at 02:21
  • This actually helps to resolve pmd violation when creating an object inside the loop cannot be avoided at all. – Harsh Raj Jul 27 '21 at 11:51