[英]Is Java application performance dependent on passing of variables to method?
对于经验丰富的程序员来说,这也许是个微不足道的问题,但是我想知道在传递变量的两种不同方法之间是否存在明显的性能差异(集合中包含大量或非常大量的数据)?
我进行了测试,但是数据结构很小,我看不出任何重大差异。 另外,我不确定这些差异是否不是由后台运行的其他应用程序引起的。
类与集合:
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 */ }
希望这可以帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.