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();
    }
}
4
  • 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. Commented Jul 14, 2016 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 if you wish. Commented Jul 14, 2016 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. Commented Jul 14, 2016 at 11:08
  • @JoséM.Carnero Thank for your suggestion Commented Jul 15, 2016 at 6:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.