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

江枫思渺然 提交于 2020-01-22 20:13:25

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/23492581/how-much-of-a-performance-difference-is-between-template-and-templateurl-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!