Should one avoid lots of use statements in a custom modules .module file? Or does it not matter? To quanity "lots", let's say, using 7 to 10 "use" statements.

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\views\Views;
use Drupal\views\ViewExecutable;
use Drupal\Component\Utility\Html;
use Drupal\node\NodeInterface;
use Drupal\Core\Cache\Cache;

I suppose for organizing code, it may be more elegant to create a service to hold custom functionality, rather than to put it directly in a custom module's .module file, but are there any performance implications for many use statements in a .module file?

  • 3
    This is more of a PHP question really - use just declares an alias, each will probably use a few CPU cycles and a modicum of RAM. Whether that has a noticeable impact depends on quite what you mean by "lots" (is 20 a lot? 50? 100? 10,000?), and the other usual environmental factors. You can always profile to be sure, but if it's something you're concerned about it's a perfect opportunity to structure your code a bit better as you say.
    – Clive
    Dec 20 '16 at 18:05
  • 1
    And for the edit: I wouldn't call 10 lots, personally. Plenty of Drupal/Symfony core classes have more than that in them and I don't think there are concerns about those (certainly haven't ever come across any). You should be fine. Very unscientifically, you could possibly assume that since you need to have those statements somewhere in the request to use their functionality, that PHP will probably spend the same amount of time processing them wherever they are. If one or more aren't actually used in a particular request, then moving them out of the .module would theoretically gain you a bit
    – Clive
    Dec 20 '16 at 18:09
  • But you're probably talking microseconds
    – Clive
    Dec 20 '16 at 18:13

The use statements alone are definitely not going to be a performance concern. I doubt that we're even talking about nanoseconds here. So that really doesn't matter. I'm guessing that this is resolved at compile time anyway.

Especially in a .module file, use statements usually grow, the more code you have, the more use statements, as a .module file is often doing many different things, implementing various hooks and so on.

If you want to optimize something, look at your actual code, forget about the use statements. Some hooks can be moved into include files, especially those that are only needed when rebuilding caches, like hook_views_data(). Other things can be done in services. But also here, the argument is most likely not going to be runtime performance, parsing code is really, really fast. It's your performance in understand the code, finding bugs, writing test and so on. Optimize for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.