0

Which is an efficient way to fetch entity label and id? Database query or entity query with entity load?

I need to get the list of all taxonomy terms in an associative array of ID and Label. I can do it loading the tree but the vocabulary has ~650 terms in it. So, loading the all the 650 terms and then building an array out of it seems like overkill.

I went with the static \Drupal::database->query() route to get the result and cache the resulting array. Just wondering if it's the right or the Drupal way of doing it.

  • 2
    Yep you're in the usual hole of efficiency vs maintainability. Theoretically the database structure could change, and your code would break. That's why you should always program to the interface, not the implementation, as they say, and use the API. But you're also right that loading 650 terms is not really acceptable when you can avoid it. So it comes down to your own knowledge and management of your own project; will it always be stored in SQL? Are you able to react quickly if there's an underlying database change that affects your code? If so, go direct – Clive Mar 28 '19 at 11:32
  • Thanks, Clive for your response. To answer about the database, yes the database will be SQL. Just another small doubt. To what limit this is acceptable? Does loading around 80-120 terms sounds fine? – Malabya Tewari Mar 28 '19 at 11:51
  • 1
    You can only really answer that by benchmarking it on your own infrastructure, under representative load. 80 terms will load fine on a powerful computer with a single request an hour, probably not so well on a shared hosting environment under heavy load. As tempting as it is to look for other peoples' experiences to answer these kinds of questions, it's rarely a good idea. There's no substitute for actually measuring the impact in the environment it's going to be affecting – Clive Mar 28 '19 at 11:56
  • Also, if uncached performance is okay, but not great, and the data doesn't change very often so that there is a high hit rate for the cached result, then it may not be worthwhile to optimize performance of the original lookup since it will not occur very often. – gapple Mar 28 '19 at 21:55

Your Answer

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

Browse other questions tagged or ask your own question.