对于有经验的程序员来说,这可能是一个微不足道的问题,但我想知道两种不同的变量传递方法之间是否存在任何显着的性能差异(收集大量或非常大量的数据)?
我已经进行了测试,但数据结构相当小,我没有看到任何显着差异。此外,我不确定这些差异是否是由后台运行的其他应用程序的干扰引起的。
集合类:
public class TestCollection
{
ArrayList<String[]> myTestCollection = new ArrayList<String[]>();
public TestCollection()
{
fillCollection();
}
private void fillCollection()
{
// here is fillng with big amount of data
}
public ArrayList<String[]> getI()
{
return myTestCollection;
}
}
以及操作集合的方法:
public class Test
{
static TestCollection tc = new TestCollection();
public static void main(String[] args)
{
new Test().approach_1(tc);
new Test().approach_2(tc.getI());
}
public void approach_1(TestCollection t)
{
for (int i = 0; i < tc.getI().size(); i++)
{
// some actions with collection using tc.getI().DOSOMETHING
}
}
public void approach_2(ArrayList<String[]> t)
{
for (int i = 0; i < t.size(); i++)
{
// some actions with collection using t.DOSOMETHING
}
}
}
问候。
最佳答案
不,这里没有真正的区别。
Java 传递对象 references
到方法,而不是整个对象的副本。这类似于 pass by reference
其他语言中的概念(尽管我们实际上是将对象引用传递给被调用的方法,按值传递)。
如果您有 C 编程背景,理解这一点很重要!
还有一些提示 - 首先,最好将列表声明为 List<...>
而不是 ArrayList<...>
,像这样:
List<String[]> myTestCollection = new ArrayList<String[]>();
其次,您可以使用改进的 for
循环列表,像这样:
// first case
for (String[] s : tc.getI()) { /* do something */ }
// second case
for (String[] s : t) { /* do something */ }
希望这有帮助:)
关于java - Java 应用程序性能是否取决于将变量传递给方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18609990/