From f7e391a912153d1ce43f9d0cf06d23121d1d49cd Mon Sep 17 00:00:00 2001 From: mgechev Date: Mon, 12 Apr 2021 14:01:26 -0700 Subject: [PATCH] perf(core): optimize getDirectives (#41525) This commit introduces the following optimizations: 1. We return an empty array for text nodes in `getDirectives` because Angular does not support attaching logic to them. This optimization improves performance of `getDirectives` significantly because text nodes often result in expensive calls to `loadLContext` since we can't resolve it from a parent node. 1. `getDirectives` now calls `loadLContext` with second argument `false` so it doesn't throw an error. This brings another significant improvement because prevents the VM from deoptimizing calls. BREAKING CHANGE: Previously the `ng.getDirectives` function threw an error in case a given DOM node had no Angular context associated with it (for example if a function was called for a DOM element outside of an Angular app). This behavior was inconsistent with other debugging utilities under `ng` namespace, which handled this situation without raising an exception. Now calling the `ng.getDirectives` function for such DOM nodes would result in an empty array returned from that function. PR Close #41525 --- .../core/src/render3/util/discovery_utils.ts | 28 ++++++++++++++----- .../test/acceptance/discover_utils_spec.ts | 2 ++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/packages/core/src/render3/util/discovery_utils.ts b/packages/core/src/render3/util/discovery_utils.ts index db5d760ff1..0546b62029 100644 --- a/packages/core/src/render3/util/discovery_utils.ts +++ b/packages/core/src/render3/util/discovery_utils.ts @@ -172,7 +172,7 @@ export function getInjectionTokens(element: Element): any[] { } /** - * Retrieves directive instances associated with a given DOM element. Does not include + * Retrieves directive instances associated with a given DOM node. Does not include * component instances. * * @usageNotes @@ -184,21 +184,35 @@ export function getInjectionTokens(element: Element): any[] { * * ``` * Calling `getDirectives` on `