There is a feature started from php 5.5 to get class name with full namespace with magic built in class
constant. For example
<?php
namespace Something\Obscenely\Long\Hard\To\Type;
class MyClass {
}
echo MyClass::class;
// Output: Something\Obscenely\Long\Hard\To\Type\MyClass
?>
Here is links for documentation and RFC http://php.net/oop5.basic#language.oop5.basic.class.class https://wiki.php.net/rfc/class_name_scalars
The question is:
If I use Zend Framework 2, for example, which known as framework with huge php arrays configs, if I use for every class name in this configs resolution method with ::class
against just full names typed like strings ''
- is there a valuable performance impact?
For example:
'controllers' => [
'invokables' => [
'\Controller\Monitor' => 'Import\Controller\MonitorController',
...
vs
'controllers' => [
'invokables' => [
'\Controller\Monitor' => MonitorController::class,
...
UPD:
My own tests
I write simple fast test to benchmark
class MyClass
{
}
class MyClass1
{
}
class MyClass2
{
}
class MyClass3
{
}
/**
* run many iteration loop for test percentage
*/
function testString()
{
$results = [];
for ($i = 0; $i < 150000; $i++) {
$results[] = [
'controllers' => [
'invokables' => [
'\Controller\Monitor' => 'Import\Controller\MonitorController',
'\Controller\Monitor2' => 'Import\Controller\MonitorController2',
'\Controller\Monitor3' => 'Import\Controller\MonitorController3',
'\Controller\Monitor4' => 'Import\Controller\MonitorController4',
]
]
];
}
return $results;
}
function testClass()
{
$results = [];
for ($i = 0; $i < 150000; $i++) {
$results[] = [
'controllers' => [
'invokables' => [
'\Controller\Monitor' => MyClass::class,
'\Controller\Monitor2' => MyClass1::class,
'\Controller\Monitor3' => MyClass2::class,
'\Controller\Monitor4' => MyClass3::class,
]
]
];
}
return $results;
}
$token = Benchmark::start('testString');
testString();
Benchmark::end($token);
$token = Benchmark::start('testClass');
testClass();
Benchmark::end($token);
exit();
And results is similar to
testString
215335.203125 Kbytes
Time: 0.2604 Seconds
testClass
215337.1640625 Kbytes
Time: 0.2508 Seconds
We can see that ::class
is faster. Run with latest php5.6.
Can it be true ?
P.S. It's not a duplicate of How to measure PHP code because:
- There is no information what I'm asking about in search engines.
I don't know how to measure performance in this question context, because for this case running benchmark not enough and difficult.
It's not simple to change thousands lines of code in real project config files.
- I want more detailed answer - not only numbers, but also why?