4

When creating a simple function, it is sometimes appropriate to encapsulate a small section of logic in a sub-function. My question is:

Assuming we will never use the calc function again, which of the following is easiest on the PHP parser when running this type of procedure?

1. A Nested Function: (PHP has to redefine calc each time:)

function doSomething($a, $b, $c) {
    $calc = function($val) { /* do some calculation */ };
    if($a>$c) return $calc($c);
    else if($a<$b) return $calc($b);
    else return $calc($c);
}

2. A Second Function: (PHP has to keep calc in global memory:)

function doSomething($a, $b, $c) {
    if($a>$c) return calc($c);
    else if($a<$b) return calc($b);
    else return calc($c);
}
function calc($val) { /* do some calculation */ }

3. A Class: (More code, and still in global memory)

class something {
    static public function doSomething($a, $b, $c) {
        if($a>$c) return self::calc($c);
        else if($a<$b) return self::calc($b);
        else return self::calc($c);
    }
    static private function calc($val) { /* do some calculation */ }
}
cronoklee
  • 6,482
  • 9
  • 52
  • 80
  • 1
    Why don't you benchmark it? There's no way to give a proper answer without full details of HOW you're planning on doing this, how often, in what context, blah blah blah. Regardless of where/how you define the function, it'll be "in global memory" anyways. – Marc B Sep 27 '16 at 16:13
  • 1
    I do not know regarding performance, but `1.` is a bad habit. `2.` is correct, `3.` let you have more control on your code by localizing your helpers in one single class (for example : `class Helpers`, where you aggregate all your little expandables functions in it). – Anwar Sep 27 '16 at 16:20

1 Answers1

2

Check this answer: anonymous function performance in PHP

As it states it usually does not make much of a difference. If you want to be sure: a lot depends on your specific PHP and server version so you will have to benchmark it.

Having said that, version 2 is more readable than version 1, but version 3 - a class with private function would be the most readable solution as your code tells other programmers clearly that calc() is not used elsewhere.

class something { static public function doSomething($a, $b, $c) { if($a>$c) return self::calc($c); else if($a<$b) return self::calc($b); else return self::calc($c); } static private function calc($val) { /* do some calculation */ } }

Community
  • 1
  • 1
Matijs
  • 2,533
  • 20
  • 24