Is it bad to use the keyword use
even though we only call a function once? E.g. I have my own typo3 extension, and I am accessing a typo3 core function in my controller, but only once.
$message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
I could also make use of use
:
use \TYPO3\CMS\Core\Utility\GeneralUtility;
...
$message = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
In my opinion the second variant is much cleaner, but are there any performance issues if I make use of use
only for one call?
In theory, there should be no performance hit. You're calling a function (and thus an autoloader) either way (which is where any performance hit will be).
To explain why, your use
statement is simply an alias. Your autoloader will do the same work either way. And it will likely be opcode cached, so any performance hit (we're talking milliseconds here, if that) will only be on the first run.
First option is faster when in namespace context and it could be more readable because of FQNS (it's a matter of taste). When there is a lot of "imports" it may indicate too high a degree of dependence and break of the single responsibility principle. So I often use inline namespacing using FQNS.
Optimizing PHP performance by using fully-qualified function calls https://veewee.github.io/blog/optimizing-php-performance-by-fq-function-calls/
Try to profile your code to get the answer.
I particularly prefer the second choice too. And there is no performance hit. You can use the second one without any concern.
It's much cleaner to import the classes and then use ::class
to reference them e.g...
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Mail\MailMessage;
$message = GeneralUtility::makeInstance(MailMessage::class);