Is it “better” to instantiate objects as needed or right in the beginning of the code? Note in the examples one may not need the functionality of obj2.
obj1 = new Object1();
obj2 = new Object2();
obj1->run;
//lots of code
if (condition) {
obj2->doThis();
}
OR
obj1 = new Object1();
obj1->run;
//lots of code
if (condition) {
obj2 = new Object2();
obj2->doThis();
}
Just 2 rules
Unnecessary object creation consumes more memory and makes program run slower. For small projects it’ll not make any significant performance difference. But for big projects or long time running Cron it becomes performance issue.