Is there any benefit, performance-wise, to declaring Apex variables as final?

In other languages (see, for instance, Swift), stating explicitly that a variable is final lets the compiler optimize the code accordingly.

Is this the case with Apex?

Answer

Too long for a comment, not a proper evaluation for 100% confidence

So if you run the following script in anonymous Apex you will find that the loop with the final variable always runs faster than the one with the non-final variable.

final Integer finalVal = 1000000;
Integer changeableVal = 1000000;
DateTime startTime;   

Long changeableDuration;
startTime = DateTime.now();
for(Integer i = 1; i <= changeableVal; i++) {
    if(i == changeableVal) {
        changeableDuration = DateTime.now().getTime() - startTime.getTime();
    }
}

System.debug('Changeable: ' + changeableDuration);

Long finalDuration;
startTime = DateTime.now();
for(Integer j = 1; j <= finalVal; j++) {
    if(j == finalVal) {
        finalDuration = DateTime.now().getTime() - startTime.getTime();
    }
}

System.debug('Final: ' + finalDuration);

Output Example:

13:52:42:612 USER_DEBUG [13]|DEBUG|Changeable: 610
13:52:43:172 USER_DEBUG [23]|DEBUG|Final: 559

It does not seem to matter the order that you code is run or the order the variables are declared, it just seems to run faster when declared final. This has only been tested on two orgs.

Attribution
Source : Link , Question Author : catalandres , Answer Author : zgc7009

Leave a Comment