[英]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.