PMD:避免在循环内实例化新对象 [英] PMD: Avoid instantiating new objects inside loops

查看:715
本文介绍了PMD:避免在循环内实例化新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了PMD规则的问题避免在循环中实例化新对象。以下是一些示例代码:

  import java.awt.Dimension; 

公共类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); //这里规则违规
}
}
}

PMD在代码中的标记位置给出了上述规则违规。如何创建类的 n 实例而不在循环中创建它们?



我知道PMD的一些规则存在争议(比如 onlyOneExit 规则。但到目前为止,我至少理解了他们背后的想法。我不明白这条规则背后的原因。有人可以帮我吗?

解决方案

对于你的具体用例,你保留对新对象的引用是没有意义的循环之后。所以你的解决方案没有其他替代方案。



更一般地说,用Java创建短期对象很便宜 *(除了GC运行的隐藏成本更频繁)。特别是,分配几乎是免费的,GC的时间主要取决于可达对象的数量 - 死对象不会增加典型GC算法的GC时间。



如果JIT检测到创建了不必要的对象,它也可以执行各种优化。



显然,创建无用的不是推荐的做法,但尝试重用对象通常会适得其反。 / p>

作为一个实际例子,你可以看一下这篇文章这表明在循环中创建一个新集比在循环之前创建一个集合并在每次迭代时清除它更便宜。



*感谢@RichardTingle链接


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?

解决方案

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

这篇关于PMD:避免在循环内实例化新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆