Search code examples
angularperformanceangular-routing

Is there any performance hit for having multiple routes pointing to the same Angular component?


I want to have multiple routes point to the same component so that I can change the default behavior of the component.

{ path: 'city/:zipCode/:cityState', component: JobSearchComponent },
{ path: 'company/:organizationId/:companyName', component: JobSearchComponent }

Is there any performance penalty by having multiple routes point to a single component like multiple instances in memory at run time or anything?


Solution

  • It will not have a significant impact, since Angular instantiates the component only when the route is active.

    That is the reason the lifecycle methods get called for a component with active route. We can confirm this with simple methods like ngOnInit and ngOnDestroy.

    Internally, the way router works is similar to adding these components to the entryComponents array. That way even though the route will be activated later during runtime, the angular compiler knows to include them in the build.

    Another thing to remember is that Angular does a first-match for the routes in router array starting from the root. Hence the order in which we add routes is important. Common example of this is we often declare not-found or non-matching i.e ** path's at the end of the routes array.

    From the Angular documentation @ https://angular.io/guide/router#configuration:

    The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.

    Considering the above the only performance will be O(N) for path matching.