PMD: Avoid instantiating new objects inside loops

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

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 

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?

回答1:

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



回答2:

for (int i = 0; i 

The Above Pmd can be resolved by

 for (int i = 0; i 

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!