Performance: List.get(index) vs List[index]

I want to know which approach is better in Salesforce when getting element from list.

Is this faster?

myList.get(0);

Or is this faster?

myList[0];

Using large list which above statement is more efficient?

Answer

The following methodology may be somewhat faulty but demonstrates a large difference. The get approach is more than 4 times slower.

Square Brackets

List<Integer> numbers = new List<Integer>();
for (Integer i = 0; i < 1000000; i++) numbers.add(i);

Integer x;
Long start = Datetime.now().getTime();
for (Integer i = 0; i < 1000000; i++) x = numbers[i];
system.debug(Datetime.now().getTime() - start); // 1233

Get Method

List<Integer> numbers = new List<Integer>();
for (Integer i = 0; i < 1000000; i++) numbers.add(i);

Integer x;
Long start = Datetime.now().getTime();
for (Integer i = 0; i < 1000000; i++) x = numbers.get(i);
system.debug(Datetime.now().getTime() - start); // 5065

Attribution
Source : Link , Question Author : Ashwani , Answer Author : Adrian Larson

Leave a Comment