0

I wonder which of the two is faster? A closure with use() or a function with parameter passing?

$mapping = [...] // array with many key, value pairs

function myFn($item, $mapping) {
   // operation, mapping
   // return modified item
}

// Function version
foreach ($items as $item) {
  $res[] = myFn($item, &$mapping);
}
// Closure version
$closure = function($item) {
   // operation, mapping
   // return modfied item
};

foreach ($items as $item) {
  $res[] = $closure($item, &$mapping);
}

Or is there a better solution?

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • 2
    Those two examples aren't equal. The first: `$res[] = myFn(...);` will store the results of the function call in the array while `$res[] = function (...) use (...) {...}` will store the function itself (unexecuted) in the array so you can executed later. Apples and oranges. `use()` is for when you need to use a variable from the current context (where you create the function) but need to execute the function later. – M. Eriksson Jan 05 '22 at 09:50
  • @M.Eriksson ok. i will imprve it. merci – Maik Lowrey Jan 05 '22 at 09:52
  • @M.Eriksson i updated and now i think it makes no difference whether closure or function. just a matter of taste?, ...? – Maik Lowrey Jan 05 '22 at 10:01
  • 2
    As I ended my previous comment: `use()` is for when you need to use a variable from the current context (where you create the function) but need to execute the function later. If you don't need this but want the caller to pass all variables from it's own scope (from when it's called), then don't use `use()`. If you want the function to be global (accessible everywhere), declare an old fashion function. If you need to be able to pass it around (pass the function to a function etc), use a closure. – M. Eriksson Jan 05 '22 at 10:04
  • @M.Eriksson In this case, it would be clear that there is no difference. Many thanks! – Maik Lowrey Jan 05 '22 at 10:08

0 Answers0