Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance impact of ng-csp directive

Enabling content-security-policy and adding the ng-csp directive prevents Angular from using Function() and eval() for certain optimization.

The doc states that performance can decrease up to 30%.

I was wondering what angular features are actually really impacted by using the ng-csp directive.

Are there workarounds, patterns or other ideas that can reduce the cost of using that directive?

like image 976
Guillaume Polet Avatar asked Mar 02 '15 18:03

Guillaume Polet


1 Answers

I did some research and the easiest way to understand the performance hit is by looking at the initial commit (see issue on Github too) that introduced CSP support in AngularJs back in 2012.

The thing is that you need to use resolutions of (sub)expressions like

a.b.c.d.e  

e.g.

user.data.books

in Angular expressions in your HTML template files. Angular parser for this used originally new Function(arguments, code) to parse these expressions. However, to support CSP you can't use new Function() or eval(). The magic number 30% seems to come from http://jsperf.com/angularjs-parse-getter/4 (source). My interpretation of the results is that code with a for loop (i.e. jumps in assembly) is slower than code with an inlined/expanded for loop.

In the light of the previous paragraphs, I don't believe there is something meaningful you can do to mitigate the performance hit. Maybe (if you are desperate) just don't use long expressions (like a.b.c.d.e.f.g.h) and use rather short ones but I don't think it's a feasible way to optimize your code.

Fast forward to 2015, AngularJs codebase changed substantially but you can see there are two parsers: ASTInterpreter (for CSP enabled) and ASTCompiler (for CSP disabled). Maybe you can put some performance evaluating code in those parsers to compare ASTInterpreter against ASTCompiler.

HTH

like image 92
Martin Vseticka Avatar answered Nov 04 '22 21:11

Martin Vseticka