six*_*ees 7 java performance new-operator
我有一个紧密的循环来搜索coprimes.一份清单primeFactors.它的第n个元素包含n的素数分解的排序列表.如果我检查c,并d使用coprimescheckIfPrimes
boolean checkIfPrimes(int c, int d, List<List<Integer>> primeFactors) {
List<Integer> common = new ArrayList<>(primeFactors.get(d)); //slow
common.retainAll(primeFactors.get(c));
return (common.isEmpty());
}
Run Code Online (Sandbox Code Playgroud)
primeFactors.get(d).retainAll(primeFactors.get(c))看起来很有希望,但它会改变我的可重用primeFactors对象.
创建新对象相对较慢.有没有办法加快这一步?我可以以某种方式利用列表排序的事实吗?我应该使用数组吗?
设置操作应该比数组操作更快。只是为了好玩,考虑尝试一下并将性能与流性能进行比较:
final Set<Integer> commonSet;
final Set<Integer> cSet = new HashSet<Integer>();
final Set<Integer> dSet = new HashSet<Integer>();
cSet.addAll(primeFactors.get(c));
dSet.addAll(primeFactors.get(d));
commonSet = dSet.retainAll(cSet);
return (commonSet.isEmpty());
Run Code Online (Sandbox Code Playgroud)
另外,请考虑使用List<Set<Integer>> primeFactors
而不是List<List<Integer>> primeFactors因为我怀疑您实际上没有质因数列表,但实际上有一组质因数。
| 归档时间: |
|
| 查看次数: |
501 次 |
| 最近记录: |