Problem/Motivation

Drupal site with 400 fields and 75 bundles has quite a lag when a view needs to execute. There is an array_filter() called in the views_entity_field_label() function that is called hundreds of times for each bundle. (once for each field basically.) or maybe twice. It just seems to be getting the list of fields and filtering that list over and over. It's fairly fast, but with so many fields and bundles, it starts to turn into .4+ seconds.

Steps to reproduce

You can just use any drupal site and put some log statements in the place where the array_filter is called and log the entity_type and bundle to see how it repeatedly does the same work for the same bundle and entity type.
The code I'm talking about is the following code

    $bundle_fields = array_filter($entity_field_manager->getFieldDefinitions($entity_type, $bundle), function ($field_definition) {
      return $field_definition instanceof FieldConfigInterface;
    });

Proposed resolution

I made a quick function:

function _mydemo_get_bundle_fields($entity_type, $bundle, $entity_field_manager) {
  static $cache;
  if(!isset($cache[$entity_type][$bundle])) {
    $cache[$entity_type][$bundle] = array_filter($entity_field_manager->getFieldDefinitions($entity_type, $bundle), function($field_definition) {
      return $field_definition instanceof FieldConfigInterface;
    });
  }
  return $cache[$entity_type][$bundle];
}

// call with
$bundle_fields = _mydemo_get_bundle_fields($entity_type, $bundle, $entity_field_manager);

and just call that to get the entity_bundles instead. This is just using static var for caching but does increase the speed quite a bit.

Remaining tasks

Convert to dependency injection or use a drupal cache backend. Would need to invalidate that somehow as well.
This is not a big improvement to small sites, but if you want to handle large numbers of fields and bundles, you will need to optimize field configs and views.
*Also, I did add similar static caching to the views_entity_field_label function so it won't need to fun more than once as well. These two issues really ate up a lot of wasted processing on large sites. I am saving significant time on the getViewsData process.

Comments

dustinyoder created an issue. See original summary.

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.