puppeteer701
puppeteer701

Reputation: 1285

How much of a performance difference is between template and templateUrl Angularjs

How much is there a performance difference between template and templateUrl?

Currently I am using template in all my directives, but because I am obsessed with performance, I would like to now, which is faster.

And if I use templateUrl + $templateCache, is this faster then only using template in directives?

Upvotes: 6

Views: 4283

Answers (3)

Robert Knight
Robert Knight

Reputation: 2927

This is a JSPerf test comparing templates in a $templateCache vs. passing the template as a string: https://jsperf.com/angular-directive-template-vs-templateurl

In this case, with a very simple template, a plain inline template is faster, presumably because it doesn't have the overhead of making an async $http request. Even though that request just loads the value from $templateCache, the service still has overhead.

Upvotes: 1

scorpp
scorpp

Reputation: 668

Faced kind of similar problem here and chrome dev tools (namely the Timeline) gave a nice picture which was then confirmed by a nice article https://thinkster.io/templatecache-tutorial/

The difference is really in $templateCache. Inline template doesn't hit it, while templates loaded with templateUrl or <script type="test/ng-template"> do. You may not notice the difference until you have few hundreds directives all having inline template being added to the page.
The thing is that for each such directive it's template will be parsed into DOM again and again which results in a) wasted time; b) wasted memory; c) lot of GC calls

As described in the article above the production option is using a build tool to fill in the $templateCache with all of your templates.

Upvotes: 2

sahb
sahb

Reputation: 56

I was asking myself the #1 question of your post another day. As no one else answered it before, and I do not have enough rep to post a comment, here are my findings after a few tests.

The best answer for your first question is that with templateURL you will have the overhead of the lazy request of the partial, when you call the directive (and it happens only at the first time; once loaded, it will behavior pratically the same as with template). The overhead is due to the extra processing of the browser with the extra request and the extra data of the headers.

The templateURL might result in poorer user experience only if you load tons of different directives at once, and all of them have small files as partials (so the small ammount of data of the headers will make a big difference).

As normally the difference is very low, I personally prefer the templateURL approach, as it makes the code cleaner and more organised.

Upvotes: 2

Related Questions