2

In apex declaring variable inside the loop will affect the performance ? What is the exact difference between declaring variables inside loop and outside loop in apex ?

Can I have any reference from salesforce site ?

Inside loop :

for (sobject sobj : sobjs) {
       String name = (String)sobj.get('name');
.............
}

Outside loop :

String name;
for (sobject sobj : sobjs) {
        name = (String)sobj.get('name');
...................
}
4

The differences:

  1. Scope: if you define name outside the loop, the name viable's scope will be accessible outside the loop. This is the major difference.
  2. Heap size: defining name inside the loop will create n instances of variables (n is the length of your array), each of them is different. Garbage collection will collect them up but no one knows when.
  3. Performance perspective, the impact is minimal.
  • Do we have any salesforce link about this ? – SANN3 Feb 16 '16 at 7:00
  • @SANN3 Don't think so. If you really want to know the answer, a proper performance test can help. However, I don't think it is even worthwhile to do it. – Lance Shi Feb 16 '16 at 7:02
  • It really depends on how you wish to use your variable. As stated above, performance impact is minimal, all you need to know is the scope of your variable use accordingly. – Shailesh Deshpande Feb 16 '16 at 7:09
  • On 2), in both forms of the code there will be no difference in heap usage as the characters of the string are located on the heap and the likely implementation is that just the reference (pointer) to the string referenced by sobj is assigned. The name variable will be located on the stack in both cases: just enough space for a single reference (pointer) is needed, 4 or 8 bytes. See e.g. What and where are the stack and heap? – Keith C Feb 16 '16 at 10:04
  • @KeithC Thank you for pointing out. But the stack memory will be different. Right? – Lance Shi Feb 16 '16 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.