function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ethan huntethan hunt 

Is instantiating new objects inside loops apex is a best practice?

Satish_SFDCSatish_SFDC

Yes you can instantiate multiple objects inside loops.
There are two governor limits which can be reached here: CPU Time and Heap Size

There used to be a Number of Code statements limit but starting winter 14 it has been replaced with the CPU Time limit.

So you have to do some testing on this to make sure your code does not exceed either of the governor limits.

Regards,
Satish Kumar

GlynAGlynA
Also, be sure you're only allocating the new objects in the loop - don't "insert" them inside the loop.  Instead, put all the new records into a list.  When the loop completes, "insert" the list of records.

-Glyn
ethan huntethan hunt
Hi GlynA,

Thanks for your suggestion. If I am doing any select operation on an object should I be creating instance inside for loop.

I want some scneraios which tells why I am instiaiting object inside loop and why I am instatiating outside the loop.

Regards