2

I have a custom module that loads one specific node to get its field value, and then uses that field to make a bunch of calculations. I've seen several comments like this one that node_load is a resource hog...

My question is if there is a significant benefit to unsetting the node object once I've retrieved my field value, and if yes what is the best way to unset it? I've googled for some time but only can find references to deleting nodes, not unsetting the object. Thanks!

1 Answer 1

2

It's advised to use node_load() rather than building your own queries.

If you worry about memory impact, you can unload it by unsetting it:

unset($node);

It would destroy the specified variable/object, however you don't have to do it as PHP should handle garbage collection internally.

Secondly the node would be only loaded in your local scope, so once PHP exits your function, it should be automatically flushed from the memory at some point.

If you're worry about memory impact, you may:

  • reduce number of modules which hook into the node objects,
  • run PHP profiler (such as XDebug) to check the memory is used the most,
  • enable Devel and its performance checking, it'll show you how much memory is used per individual page,
  • implement memory caching (instead of using database layer), such as redis or memcached

    See: How do you improve Drupal performance?

2
  • 2
    Please note that node_load eventually runs DrupalDefaultEntityController::load which will place every loaded entity in the Drupal static cache for quick retrieval during a possible second load in the same request. Unsetting the $node variable will free up some memory but this is such a small optimization that you will not notice the difference (and the static cache still consumes memory). If there are also other modules hooking in the loading of the node, it could be beneficial for you to also use node_load and benefit from the static cache (preventing a second similar query). Oct 16, 2015 at 21:44
  • It would be really helpful to know if it's possible to tell Drupal to clear it's internal static cache.
    – Brian
    May 16, 2017 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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