+ Start a Discussion

How does Garbage collection works in apex?

Hi All,


I am wondering how the garbage collection works in salesforce? I am building a batch process and I am expecting the execute method to be called 1000 times with batch size of 50. So each time the execute method is called I am passing a looping through the List of sobjects and casting them to the Account object and assigning them to a List. The List variable defined in the execute method it self. So that mean's I would have creatd 1000 different variables and I am sure this will make use of memory. I dont' know how the garbage collection works and what the best practice is. I was thinking defining the List variable as a local variable within the batchable class and then cleaning up the list and adding the new list of records each time the execute method is called.  Can someone explain how the memory is allocated for these objects? Thanks.




Each invocation of the execute method runs in its own transaction, so you don't need to worry about what has gone before or may come after.  All you really need to concern yourself with is not exceeding governor limits.


(This is a slightly simplistic view and if your code burns a lot of resource you can expect to hear from Salesforce, but for your scenario its not anything to worry about).




Garbage collection is undocumented.


Here's what I think I know:


* Heap size is apparently tracked as a system variable that is adjusted after every line of script.

* Symbols (i.e. variable names) do not use heap space, only the variables they contain. Null variables, therefore, take no heap space.

* Governor limits appear to be checked only periodically, so a brief burst over the legal limit is possible, but not advised in any case.

* Removing an array index, assigning a null value, etc, appears to immedately free heap space.

* Assigning a new variable, adding an array index, etc, appears to immediately consume heap space.


It's important to note, I guess, that the question of garbage collection is pointless, because either you exceed your limit and you get the boot, or you stay within the limits, and you do not get the boot. Just know that garbage collection works in your favor (i.e. it assumes you're really trying to not exceed any limits), by at least appearing to immediately reclaim free heap space.


I suspect that the heap is periodically defragmented, but there is literally no way to prove or disprove that theory, since memory addresses are never exposed to the developer.