ellabeauty
ellabeauty

Reputation: 2599

Anonymous functions more expensive than normal functions?

It appears that anon functions are objects, so I guess that the function is a method of that object. Does that mean they take more resources than a normal function?

Upvotes: 0

Views: 280

Answers (2)

ashein
ashein

Reputation: 487

I did a small test on relative run times. The script is like:

<?php
// long execution time required
ignore_user_abort(1);
set_time_limit(0);

// some presumingly costly function
function mathematics() {
  $c = 0;
  for ($i = 0; $i < 1000; $i++) $c += rand(0, 1000);
  return $c / 1000;
}

$lambda = function() {
  // same as mathematics()
};

// Executing normal function
for ($i = 0; $i < 50000; $i++) mathematics();

// Now onto lambda function
for ($i = 0; $i < 50000; $i++) $lambda();
?>

Profiling with xdebug and feeding the cache into cachegrind yields:

mathematics(): 31,804,288
closure:       31,719,438

I think it's safe to assume that the difference in time required to run is negligeable.

Upvotes: 1

Churk
Churk

Reputation: 4637

Taking more resource in terms of what? Memory? or Hard drive space?

Memory, no, php loaded everything, as soon as u include a file, the entire file gets read. So if a function acts as a variable within a method, then it will get executed automatically, and that may take X amount more memory space. While a function defined as a function will not get executed until it is called upon. So if you have a function acting as a variable not being used (declared and never used). Then yes, it would take up more memory.

Hard drive space: It takes up the same amount.

Upvotes: 3

Related Questions