Wessel van der Linden
Wessel van der Linden

Reputation: 2622

Namespace or class with static methods?

I want to group several methods. These methods do not contain any class data, so are therefore static. PHP has 2 options to do this; by putting them in a namespace or in a class. Example:

// option 1
namespace Renderer;
function render()
{

}
// invoke with 'Renderer\render()'

// option 2
class Renderer
{
    static function render()
    {

    }
}

// invoke with 'Renderer::render()'

Is there any difference between those 2 options in performance? I mean, my idea is that the class declaration creates an object with the static methods in the RAM. So therefore uses slightly more memory than the namespace. Or does that not matter?

Upvotes: 0

Views: 690

Answers (2)

IMSoP
IMSoP

Reputation: 97898

"Or does that not matter?" No, it really doesn't.

Structuring your code differently to be more efficient in tiny memory impacts like this is concentrating on entirely the wrong problem.

PHP is a very high-level programming language, most of whose features are implemented for the convenience of the programmer, in that they allow you to write expressive, structured, maintainable code. Using those features effectively is what you should be thinking about, e.g.:

  • A static class can still have private methods and properties, and even use polymorphism thanks to Late Static Binding
  • A namespace can collect both classes and stand-alone functions into a coherent grouping, and can be organised hierarchically. They also allow importing items into the scope of a different namespace for convenience, with PHP 5.6 adding support for aliasing imported functions as well as classes.

If, for some reason, you really do need to worry about micro-optimisation of speed or memory, you should not be writing in a high-level, VM-executed, language like PHP, but in one that allows much closer control of such things, such as C. For most people, the convenience of high-level programming constructs massively outweighs the tiny impact on modern hardware of executing them.

Upvotes: 1

webbiedave
webbiedave

Reputation: 48887

the class declaration creates an object with the static methods in the RAM

An object is not created unless instantiation occurs, i.e., $myObject = new MyClass();

Functions will go into the symbol table after parse regardless if they are part of a class definition or not.

Is there any difference between those 2 options in performance

It's negligible and shouldn't be your primary concern. Look for better organization/readability instead.

Encapsulating the methods in a class definition provides better organization. It also allows autoloaders to work with it.

Upvotes: 3

Related Questions