Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Angular2 Ahead of Time (AoT) compilation work?

Angular 2 comes with the new feature called Ahead of Time (AoT). But after some reading, I still can't really understand it. How does it works? And how will it brings better performance? How is it different to JIT?

Thank you.

like image 383
user1995781 Avatar asked Sep 13 '16 07:09

user1995781


1 Answers

Angular uses declarative binding in views and decorators on modules, directives, pipes that need to be interpreted by JS in the browser to do what they are intended for.

The offline template compiler replaces declarative binding and decorators by generated static code.

This make Angular2 component instantiation and initialization faster because JS has less work to do. The "compilation" of the component has already been done before the application was served to the client.

If you don't use other features that require it at runtime, the platform-browser-dynamic can be omitted and doesn't need to be loaded into the browser at all.

There are some discussions whether the generated code doesn't outsize the browser-dynamic platform size but as far as I know the Angular2 team does a lot of experimenting and benchmarking to ensure the best performance.

From the AoT cookbook

Angular components consist of a mix of standard html and Angular syntax (e.g. ngIf, ngFor).

Expresions like ngIf and ngFor are specific to Angular, so there is no way for the browser to execute them directly.

Before the browser can render the application, Angular specific code and templates have to be converted to regular executable JavaScript. We refer to this step as compilation.

By default compilation is executed by the browser at runtime, during what is called Just in Time compilation (JIT). It's called "Just in Time" since compilation happens on the fly as the application loads.

The downside to JIT compilation is a runtime performance penalty. Views take longer to render because of the compilation step. It also forces us to download the Angular compiler along with our application code since we will need the compiler at runtime.

like image 95
Günter Zöchbauer Avatar answered Sep 17 '22 23:09

Günter Zöchbauer