gpt4 book ai didi

Java android性能数组: access class getter directly or create local copy

转载 作者:行者123 更新时间:2023-11-30 02:50:32 26 4
gpt4 key购买 nike

从性能的角度来看,我有一个

class someClass {
private List<type> data;
public List<type> getData()
{
return data;
}

}

class someOtherClass {
private someClass instance;
private someMethod() {

// heavy loop
for (...) {

}
}

}

在繁重的循环中直接调用效率更高(可能不止一次)

instance.getData().get(index).someOtherMethod(); 

或者更适合在循环之前做这样的事情:

localData = someClass.getData();

并使用 localData 来满足循环内的每个需求?


编辑:假设 getData() 方法做了一些其他事情,编译器优化仍然有效?

class someClass {
private List<type> data;
public List<type> getData()
{
makeSomething();
return data;
}

}

最佳答案

如果高效是你真正想要的,get(index)O(n) 加上你在一个 forloop 中,这使得 O(n^2 ) 大 O

与其使用常规的 forloop,不如使用增强的 forloop

示例:

for(someClass s: yourList){} 

现在不调用 get(index) 使用增强的 forloop 将使其成为 O(n) 而不是 O(n^2)

关于Java android性能数组: access class getter directly or create local copy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24258625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com