Thursday, August 18, 2016

Tips for Angular Js Perfomance

Introduction
AngularJS is powerful framework to create large scale web application. 
Provides lot of special features to develop the single page performance driven 
web application.
  1. ·        Data Binding
  2. ·        Directive
  3. ·        Services
  4. ·        Routing
  5. ·        Controllers
  6. ·        Dependency Injection

Angular JS is beyond above mentioned concepts.
 Being MVVM framework applications maintained in single source of model to synch 
data between various layers. We can build reusable components with declarative approach with directive in place.
Any of the modern MVC frameworks fails on the performance concerns.
 It obviously depends on understanding core process how such framework works and how to get best out of it.
This newsletter summarizes top critical points to be considered while developing angular application to gain the performance.

Performance Angular
Angular is sooooooo SLOW!  Well many of us over time experienced or heard this phrase from people saying. AngularJS is one of the modular frameworks with all performance enhancements built in, but they can’t solve all our problems.
No matter how fast the framework, we can all create sluggish code through bad practices and not understanding key concepts that help it perform well.

Performance of angular is highly depends on digest cycle and scope hierarchy.
 Angular is not basically slow. You can make it slow relatively easy by coding the way it should not be.
I have listed here top performance points which I had come across developing angular application over the years.



1.   Restrict ng-repeat Usage

One of the amazing directives from Angular JS is ng-repeat. We cannot even think about an app based on angular without its presence as a beginner.
Ng-repeat quietly affect performance when not used properly. Having nested ng-repeats is a quick and easy way to increase
your watcher count exponentially and should be avoided if at all possible.



tick

cross

1.      Use  ng-repeat  with "track by" expression  to boost performance

<li ng-repeat="item in array track by item.id></li>


1.      Refrain binding function to ng-repeat. Binded function called every time of digest cycle.

<tr ng-repeat="user in getUsers()">…</tr>

2.      Applying filter in ng-repeat is expensive and called for each digest cycle. Instead filter in controller and bind it.

<tr ng-repeat="product in products | filter: { color: 'red' }
">…</tr>



2. Prefer ng-if/ ng-switch over ng-show

Use ng-if in place of ng-show wherever possible. ng-show merely hides the element with display none and bounded
element would still hang in DOM.

ng-if  directive add or remove the elements based on demand which avoids the unnecessary DOM rendering.
Therefore the additional DOM elements and data-bindings are evaluated on demand.



tick

cross

1.      Here form would not render and model inside evaluated on demand

<button ng-click="item.showForm = !item.showForm”>Show</button>

<form ng-if=”item.showForm”>
  <input type=”text” ng-model=”item.userName” name=”username” />
</form>


1.      userName model value would be still evaluated and add the burden to watchers.

<button ng-click=" item.showForm = !item.showForm”>Show</button>

<form ng-show=”item.showForm”>
  <input type=”text” ng-model=”item.userName” name=”username” />
</form>


3. Bind Once When Possible

One of the reasons being Angular App slowness is more bindings in the app.  When watchers set in application angular
internal engine hold the responsibility to keep track of changes and update wherever required.

Applying changes to the bounded model set by watchers is called digest cycle. The more watchers present will take longer
digest cycle result in slow and unresponsive application.

Angular becomes slower with around 2,000 bindings due to the process behind dirty-checking. Lesser binding will boost up performance!



tick

cross

1.      Use one way binding moreover possible. The below fragment will be updated on page load and watcher would be removed after the first digest cycle.


<h1> {{ ::appTitle }} </h1>



1.      Do not bind the function in the view. Instead evaluate in controller and bind it.

<div> {{ getUserName()}} </div>




4. $watchCollection and $watch

$watch() function allow us to create custom watchers in angular application to manipulate the data on change. By default the deep checking of the reference would not be done on $digest cycle.

The $watch() function takes a third, optional argument for "object equality." If you pass-in "true" for this argument, AngularJS will actually perform a deep-object-tree comparison. This means that within each $digest, AngularJS will check to see if the new and old values have the same structure (not just the same physical reference).

This causes app to track larger foot print; however, the deep object tree comparison is far more computationally expensive. Instead we could use $watchCollection() to fulfill that scenario.


tick

cross

$watchCollection() works by comparing physical object references; however, unlike the $watch() function, the $watchCollection() goes one-level deep and performs an additional, shallow reference check of the top level items in the collection.

$scope.$watchCollection(
    "collection",
    function( newValue, oldValue ) {
       // Code on change
    }                                                
 );



$scope.$watch("collection",
     function( newValue, oldValue ) {
            // Code on change
     },
     true // Object.
     );



5. Limit Filter Usage      
        
Filters are powerful service provided in angular which transform your application data at runtime based on business need.
Even though filters are allowed to place it in the view Its good practice to transform the data in the controller applying
necessary filters before binding.

When filters are applied in the view with pipe symbol which in turn creates watchers. If digest cycle is triggered with
any changes to the model all the filters would execute.

This again adds heavy lifting to angular engine to keep track and run filter function on each digest cycle.








tick

cross

Translating in controller and bind it.

$scope.description = $translate.instant(‘Title Description’);


– In HTML {{::description}}


Avoid binding filter in the view. This filter will run through each digest cycle irrespective of changes.


$scope.decription = ‘Title Description’;

{{ description | translate}}




6. Disable debug info in production    

Angular provides all the necessary information for debugging along with other features. This debugging supported through adding some addition properties and classes to the DOM.  Manipulating attributes and classes will also cost to performance
and expensive operation on DOM elements.

We need to turn off this debug flag while distributing the code to production.


tick




app.config(['$compileProvider', function ($compileProvider) {

// disable debug info
  $compileProvider.debugInfoEnabled(false);
}]);





7. $digest over $apply  

$scope.$apply() is costly operation which typically trigger the digest cycle from root scope. Calling all the watchers to recheck and update the value.

We should use $scope.$digest() instead of $scope.$apply() when we know the $scope changes are needed to update in the
child node. Because $digest() will propagate the update downwards through child node from where it started. 
  

8. $interval and $timeout

Do not use the standard JavaScript setTimeout and setInterval function over Angular wrappers functions such as$timeout and $interval to avoid manually calling $scope.$apply().

These wrapper functions internally call $scope.$apply when handler is completed execution. One important thing to take
care of setting $interval or $timeout is setting optional invokeApplly parameter.

By default the third parameter is set to true which indicated angular engine to trigger $scope.$apply internally.
InvokeApplly parameter should set to false explicitly if there are no $scope updating is required.







tick

cross

$timeout(function(){
   // Snippet here will not
  // trigger digest   cycle
},
4000,
true);

// This function change the scope we leave the invokeApply to default value.


$interval(function(){
   $scope.name = ‘hello’;
},
4000);



function timerCallback(){
   // Snippet here not updating $scope
}


$timeout(timerCallback,4000,true);

$interval(timerCallback,4000,true);





9. Unregister Watchers and Destroy Polling

$watch() function is used to create custom watchers in application to do some operation based on model changes.
When this watch is registered and called it returns a callback function.

This function holds unregistering instruction for the respective watchers. Unregistering must be done calling this
function to avoid the memory leak.

Similarly $timeout and $interval ids must be cleared using $timeout.cancel() function after its usage and scope destroy.


Tuesday, June 7, 2016

Understand $emit, $broadcast in Angularjs



$emit dispatches an event upwards , $broadcast dispatches an event downwards


$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).

$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.



$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.

$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.


  1. var app = angular.module('myapp', []);
  2. app.controller("mainctrl", function ($scope) {
  3. $scope.raise = function (msg) {
  4. $scope.$broadcast('event-name', { message: msg });
  5. };
  6. });

  7. app.controller("subCtrl", function ($scope) {
  8. $scope.$on('event-name', function (event, args) {
  9. $scope.message = args.message;
  10. console.log($scope.message);
  11. });
  12. });

Monday, March 28, 2016

Difference between "=", "@" and "&" - Angular JS


All three bindings are ways of passing data from your parent scope to your directive's isolated scope through the element's attributes:
  1. @ binding is for passing strings. These strings support {{}} expressions for interpolated values. For example: . The interpolated expression is evaluated against directive's parent scope.
  2. = binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope. Changes to one model affects the other, and vice versa.
  3. & binding is for passing a method into your directive's scope so that it can be called within your directive. The method is pre-bound to the directive's parent scope, and supports arguments. For example if the method is hello(name) in parent scope, then in order to execute the method from inside your directive, you must call $scope.hello({name:'world'})
I find that it's easier to remember these differences by referring to the scope bindings by a shorter description:
  • @ Attribute string binding
  • = Two-way model binding
  • & Callback method binding
The symbols also make it clearer as to what the scope variable represents inside of your directive's implementation:
  • @ string
  • = model
  • & method
In order of usefulness (for me anyways):
  1. =
  2. @
  3. &

There are three ways scope can be added in the directive:
  1. Parent scope: This is the default scope inheritance.
The directive and its parent(controller/directive inside which it lies) scope is same. So any changes made to the scope variables inside directive are reflected in the parent controller as well. You don't need to specify this as it is default.
  1. Child scope: directive creates a child scope which inherits from the parent scope if you specify the scope variable of the directive as true.
Here, if you change the scope variables inside directive, it wont reflect in the parent scope, but if you change the property of a scope variable, that is reflected in the parent scope, as you actually modified the scope variable of the parent.
Example,
app.directive("myDirective", function(){

    return {
        restrict: "EA",
        scope: true,
        link: function(element, scope, attrs){
            scope.somvar = "new value"; //doesnot reflect in the parent scope
            scope.someObj.someProp = "new value"; //reflects as someObj is of parent, we modified that but did not override.
        }
    };
});
  1. Isolated scope: This is used when you want to create scope that does not inherit from the controller scope.
This happens when you are creating plugins as this makes the directive generic, since it can be placed in any html and does not gets affected by its parent scope.
Now, if you dont want any interaction with the parent scope, then you can just specify scope as empty object. like,
scope: {} //this does not interact with the parent scope in any way
Mostly this is not the case as we need some interaction with the parent scope, so we want some of the values/ changes to pass through. For this reason we use:
1. "@"   (  Text binding / one-way binding )
2. "="   ( Direct model binding / two-way binding )
3. "&"   ( Behaviour binding / Method binding  )
@ means that the changes from the controller scope will be reflected in the directive scope but if you modify the value in the directive scope, the controller scope variable will not get affected.
@ always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}.
= is birectional so if you change the variable in directive scope, the controller scope variable gets affected as well
& is used to bind controller scope method so that if needed we can call it from the directive
Advantage here is that, the name of variable need not be same in controller scope and directive scope.
Example, directive scope has a variable "dirVar" which syncs with variable "contVar" of the controller scope. This gives a lot of power and generalisation to the directive as one controller can sync with variable v1 while another controller using the same directive can ask dirVar to sync with variable v2.
Below is the example of usage:
The directive and controller are:
 var app = angular.module("app", []);
 app.controller("MainCtrl", function( $scope ){
    $scope.name = "Harry";
    $scope.color = "#333333";
    $scope.reverseName = function(){
     $scope.name = $scope.name.split("").reverse().join("");
    };
    $scope.randomColor = function(){
        $scope.color = '#'+Math.floor(Math.random()*16777215).toString(16);
    };
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: {
            name: "@",
            color: "=",
            reverse: "&"
        },
        link: function(element, scope, attrs){
           //do something like
           $scope.reverse(); 
          //calling the controllers function
        }
    };
});
And the html(note the differnce for @ and =):
<div my-directive
  class="directive"
  name="{{name}}"
  reverse="reverseName()"
  color="color" >
</div>

Tuesday, October 6, 2015

Runtime Javascript anonymous functions

Javascript anonymous functions are function that are dynamically declared at runtime.
In other way function can be created without function name,
Javascript nomal function(with name) will be created using function declaration
But, Anonymous function uses function operator.


Here’s a example of a ordinary function:
  1. function abc()
  2. {
  3.   alert("Created by function declaration");
  4. }
  5. abc();
Here’s the same example created as an anonymous function:
  1. var abc = function()
  2. {
  3.   alert("Created by function operator");
  4. }
  5. abc()
Above code, anonymous function is assigned to a variable abc. Javascript function is also a object like any other object. Hence function objects also can be assigned or passed as parameter.


Sunday, October 4, 2015

Javascript prototype is easy

  1. Javascript prototype is quite fuzzy word for javascript developers in the beginning.
  2. Prototype is the property which is available for all javascript functions by default.
  3. This property helps to attain inheritance in javascript.
  4. As most of them  aware of classical inheritance concept i.e inherits the methods and properties from parent class.
  5. But, In javascript there is no class keyword to achieve inheritance.
  6. Javascript is function based object orient programming language.

Find the following simple snippet to understand prototype.

function abc() {
}

Prototype methods and property created for function abc

abc.prototype.testProperty = 'Hi, I am prototype property';
abc.prototype.testMethod = function() { 
   alert('Hi i am prototype method')
}

Creating new instances for function abc

var objx = new abc();

console.log(objx.testProperty); // will display Hi, I am prototype property

objx.testMethod();// alert Hi i am prototype method

var objy = new abc();


console.log(objy.testProperty); //will display Hi, I am prototype property

objy.testProperty = Hi, I am over-ridden prototype property

console.log(objy.testProperty); //will display Hi, I am over-ridden prototype property

Same way prototype methods can be overridden in the instance

Note: If you are still not able to understand please comment your query.

Sunday, September 6, 2015

Why Angular JS


  • Allows to write Single page application in better way.
  • Its a structural framework, to create dynamic web apps.
  • Uses HTML as template , let developer to extend HTML syntax.

Serverless vs. Kubernetes: A Beginner's Guide

Serverless vs. Kubernetes: A Beginner's Guide Trying to decide between serverless and Kubernetes? Here's a simple breakdown: 🔹 Choo...