In PHP there are two ways to use namespaced classes:
Using an import (use
) declaration:
use TheClassNameSpaceMyClass; ... public function myFunction(MyClass $myClass) { // Things to do }
Using the fully qualified name every time you use the class:
public function myFunction (TheClassNameSpaceMyClass $myClass) { // Things to do }
In terms of performance, which approach is better?
Advertisement
Answer
Both approaches are functionally equivalent.
There is no performance advantage to either.
The code is compiled ahead of execution, and neither style has an impact or compile or execution time.
Verifying it yourself is trivial writing a very simple benchmark:
// Foo.php namespace Bar; class Foo { public int $a; public function __construct(int $a) { $this->a = $a; } }
// test.php require 'Foo.php'; function footest(BarFoo $a): void { $a->a++; } $t1 = microtime(true); $foo = new BarFoo(1); for ($i = 0; $i < 200000000; $i++) { footest($foo); } $t2 = microtime(true); echo $t2 - $t1;
Just run this as is, and again using an import (use
) statement, and you’ll get virtually identical results.