Apex variable declaration and for loop performance

I found that a few times in a different projects and now I’d share this common mistake with you.

[code lang=”java”] String someVariable = ”; … // 50 lines of code between declaration and first use for (Account acc: accounts) { someVariable = acc.Some_Field__c; // rest of the loop } [/code]

Actually I really hate to find something like that in my codebase. What’s wrong with this code? Just one moment – the string variable which is on scope of for loop is declared outside of the for loop. That was an optimisation for some old compilers for C/C++ a many years ago. But modern compilers can optimise your code much better that you. So, just let them do that.

[code lang=”java”] for (Account acc: accounts) { String someVariable = acc.Some_Field__c; // rest of the loop } [/code]

This code will be much effective that the first one. I did a few tests on Apex.

[code lang=”java”] String s1; Datetime start = System.now(); for (Integer i = 0; i > 100000; i++) { s1 = String.valueOf(i); } System.debug( System.now().getTime() – start.getTime()); [/code]

with results:

USER_DEBUG [6]|DEBUG|3006 USER_DEBUG [6]|DEBUG|3029 USER_DEBUG [6]|DEBUG|3189 USER_DEBUG [6]|DEBUG|3256 USER_DEBUG [7]|DEBUG|3346

and run

[code lang=”java”] Datetime start = System.now(); for (Integer i = 0; i < 100000; i++) { String s1 = String.valueOf(i); } System.debug( System.now().getTime() – start.getTime());

[/code]

with the following results:

USER_DEBUG [5]|DEBUG|2954 USER_DEBUG [5]|DEBUG|2978 USER_DEBUG [5]|DEBUG|3102 USER_DEBUG [5]|DEBUG|3176 USER_DEBUG [5]|DEBUG|3205

Runs through 300.000 iterations:

Variable declared outside the loop USER_DEBUG [6]|DEBUG|8260 USER_DEBUG [6]|DEBUG|8415 USER_DEBUG [6]|DEBUG|8606 USER_DEBUG [6]|DEBUG|8614 USER_DEBUG [6]|DEBUG|8739 USER_DEBUG [6]|DEBUG|8852 USER_DEBUG [6]|DEBUG|8940 USER_DEBUG [6]|DEBUG|9109 USER_DEBUG [6]|DEBUG|9184 USER_DEBUG [6]|DEBUG|9267 USER_DEBUG [6]|DEBUG|9292 USER_DEBUG [6]|DEBUG|9461

Variable declared inside the loop USER_DEBUG [5]|DEBUG|8093 USER_DEBUG [5]|DEBUG|8135 USER_DEBUG [5]|DEBUG|8448 USER_DEBUG [5]|DEBUG|8598 USER_DEBUG [5]|DEBUG|8785 USER_DEBUG [5]|DEBUG|8948 USER_DEBUG [5]|DEBUG|9032 USER_DEBUG [5]|DEBUG|9087 USER_DEBUG [5]|DEBUG|9122 USER_DEBUG [5]|DEBUG|9260 USER_DEBUG [5]|DEBUG|9330 USER_DEBUG [5]|DEBUG|9347

*Results was sorted for better readability

As you can see the code which use a declaration of variables inside the loop works faster or with the same time of execution. But such code is much more supportable and readable.

[apex][best practice][refactoring time][salesforce]