1

I want to ask a noob question regarding the server performance.

Assume that each class contain 1000 line codes with same performance wight .

If I want to use a function belongs to the another. I found that there are 3 ways to do that.

  1. Inside class $this->Another_Class = new Another_Class
  2. Use static Another_Class::Wanted_Function()
  3. Global global $Another_Class

May I ask in term of server performance, are they the same?? or do I have alternative except magic call?

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
Micah
  • 4,254
  • 8
  • 30
  • 38
  • 6
    Don't think in terms of server performance - it is going to be negligible. This is more a style question (and a good one, +1) – Pekka Jan 17 '13 at 21:54
  • 1
    If instantiating one class is the whole of your code, then it might make a difference for server performance. With a codebase slightly larger than that one line, certainly not measurable. Else: profiler. – mario Jan 17 '13 at 21:55
  • 4
    Micro optimization is the root of all evil. Beside this: A 1000 LOC-class is very big ;) Consider refactoring – KingCrunch Jan 17 '13 at 21:55
  • 1
    Related: [In a PHP project, what patterns exist to store, access and organize helper objects?](http://stackoverflow.com/q/1812472) – Pekka Jan 17 '13 at 21:56

2 Answers2

1

I strongly suggest you do not use globals for anything.

As for whether to use static or instantiated classes... that's entirely up to what you're trying to do. A static member function is essentially the same as a namespaced function that has the ability to access other static member functions/variables.

Instantiating a class is technically slower than accessing a static class, but that's only the case if you have logic that is run when the __construct() and class variable initialization happens.

Ian
  • 24,116
  • 22
  • 58
  • 96
1

Globals should be avoided at all times, and static generally should be avoided too unless it is really necessary as they are not good for code reuse.

Also, you might want to take a look at such concepts as Inversion of Control and Dependency Injection. In short you should prefer not to instantiate dependencies within class, but inject it.
Simple example:

class Example
{
    protected $foo;

    public function setFoo($foo)
    {
        $this->foo = $foo;
    }

    public function doSomething()
    {
        $this->foo->callFooMethod();
    }
}

$example = new Example();
$example->setFoo(new Foo);
$example->doSomething();
Xerkus
  • 2,695
  • 1
  • 19
  • 32