Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

php - Is there a difference between using use and passing the class path to a method?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...