1

I wonder about performance between "Create object and pass it to function" or "Create object inside function" - I think when create object inside function better cause after the function finished, all local var will be released. So i think 2 better than 1.

1) $a = new A();
test($a);

2) test1(){$a=new A(); ..}

But i wonder if the function called inside a loop, so the 2 case will create object each time. Maybe it loot more resource, time than 1? Here my test code but maybe it not perfect to answer that

$start_mem = memory_get_usage();

var_dump($start_mem);
$start = microtime(true);
for($i=0; $i < 10000; $i++) {
  test();
}
$end = microtime(true);
$end_mem = memory_get_usage();
echo "Timne: ". ($end - $start). "\n";
var_dump($end_mem);
echo "Mem: ". ($end_mem - $start_mem). "\n";
######### test 2
// $start_mem = memory_get_usage();
// var_dump($start_mem);
// $start = microtime(true);
// $obj = new PingSitemap();
// for($i=0; $i <10000; $i++) {
//     test1($obj);
// }

// $end = microtime(true);
// $end_mem = memory_get_usage();
// echo "Timne: ". ($end - $start). "\n";
// var_dump($end_mem);
// echo "Mem: ". ($end_mem - $start_mem). "\n";

function test() {
    $obj = new PingSitemap();
    for($i=0; $i < 1000; $i++) {
        $obj->counta();
    }
}

function test1($obj) {
    for($i=0; $i < 1000; $i++) {
        $obj->counta();
    }
}
deceze
  • 510,633
  • 85
  • 743
  • 889
Cun Gau
  • 19
  • 1
  • I never wondered about it as I usually decide on this matter based on if I need the object outside of the function as well or not but this is certainly an interesting question. Gonna make a few test cases myself at home later. – PockeTiger Jul 14 '16 at 10:34
  • If you use the second option your function have a hard dependency, if object A disapears or is modified the function probably crash. Read about [dependency injection](http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146) if you wish. – José M. Carnero Jul 14 '16 at 10:59
  • Performance is seriously the least of your concerns here. *Meaning* of the code and considerations about hardcoding dependencies are much more significant. – deceze Jul 14 '16 at 11:08
  • @JoséM.Carnero Thank for your suggestion – Cun Gau Jul 15 '16 at 06:33

1 Answers1

1

I think the second is better, because is a local variable, so the variable will be destroyed when the script get the end of the function.

Maybe this post can help you: Does PHP free local variables immediately after the function ends?

On the other hand, if you want to make a loop I think the same that you.

Community
  • 1
  • 1
dimasdmm
  • 318
  • 4
  • 15