简体   繁体   English

如果方法参数是原始int,那么方法内循环中的myArrayList.contains(primitiveArg)效率极低还是可以?

[英]If method argument is a primitive int, then myArrayList.contains(primitiveArg) within a loop within a method is enormously inefficient or OK?

I have code like this: 我有这样的代码:

public int getDistanceToNumber(int number) {
    List<Integer> tuple5 = null;
    int distanceCounter = 0;
    for (int i = 0; i < allDraws.size(); i++) {
        tuple5 = allDraws.get(i).getTupleAsList();
        if (tuple5.contains(number)) {  // autoboxing primitive ?

        }

    }

    return 0;
}

The question is - shall I make method argument Integer like int getDistanceToNumber(Integer number) for autoboxing from primitive into Integer to happen only once, or there is no performance issue. 问题是-我是否应该使方法参数Integer像int getDistanceToNumber(Integer number)从原语自动装箱到Integer仅发生一次,否则不会出现性能问题。

This piece of code inside loop runs over 100K times... 这段循环内的代码运行了超过10万次...

You should test that under a JMH . 您应该在JMH下进行测试。

  • You can avoid the boxing problem by using a Integer.valueOf(int) once and passing it to List::contains(Object) . 您可以通过一次使用Integer.valueOf(int)并将其传递给List::contains(Object)来避免装箱问题。
  • The compiler may be efficient enough to understand that number is never changed and do that for you. 编译器可能有足够的效率来了解该number永远不会更改,并为您执行此操作。

For the rest, without more information (type of allDraws ?), there might be other optimization to do before boxing conversion. 对于其余的内容,如果没有更多信息( allDraws类型?),在装箱转换之前可能还需要进行其他优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM