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

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

I don't know if Salesforce changed its algorithms, but I just tested it, both in my Sandbox and Production, and it turns out the method List.get() is almost always faster than square brackets [i].

My first attempt, running List.get() prior to running square bracket:

// Square Brackets vs List.get()
   List<Integer> numbers = new List<Integer>();
   for (Integer i = 0; i < 1000000; i++) numbers.add(i);

   Integer x;

// List.get()
   Long startBracket = Datetime.now().getTime();
   for (Integer i = 0; i < 1000000; i++) x = numbers.get(i);
   System.debug(Datetime.now().getTime() - startBracket); // 1422

// Square Brackets
   Long startGet = Datetime.now().getTime();
   for (Integer i = 0; i < 1000000; i++) x = numbers[i];
   System.debug(Datetime.now().getTime() - startGet); // 1528

Then I ran it again. The results:

  • get: 1575
  • brackets: 1859

Maybe the problem was the execution order? Well, I've inverted it, just in case:

// Square Brackets vs List.get()
   List<Integer> numbers = new List<Integer>();
   for (Integer i = 0; i < 1000000; i++) numbers.add(i);

   Integer x;

// Square Brackets
   Long startBracket = Datetime.now().getTime();
   for (Integer i = 0; i < 1000000; i++) x = numbers[i];
   System.debug(Datetime.now().getTime() - startBracket); // 1526

// List.get()
   Long startGet = Datetime.now().getTime();
   for (Integer i = 0; i < 1000000; i++) x = numbers.get(i);
   System.debug(Datetime.now().getTime() - startGet); // 1352

I've repeated this test several times, in both Sandbox and Production, with similar results.

Could you guys please repeat the test on your end just in case? Because it seems now it's faster to use List.get().