Sunday, May 31, 2015

Javascript optimisation

Javascript is client side language and is run on browser. As the code would be run on client side we need to reduce the time taken for execution of response.Of course, most of the time it is not needed in everyday JavaScript. There are some things to keep in mind about speed optimization. We need to design out algoritm in an optimsed way so that it would take less time for execution.  As the code is run on client side we must structure our code well so that end user should not have to wait for page load. We just cant consider javascript but we need to concentrate on structuring of html,css as well. Minimise the usage of javascript so that it incress the performance of page.

In this blog I will concentrate more on good habbits of javascript coding. We should know when our javascript needs to be called. Sometimes we may need function to be executed on document ready and sometimes on page load . For example attaching the event control for page should be handled after page load as it is not required on document ready. Understand and choose the right way.

"Best practise is nothing but choosing the right way of doing it".



1.      Reduce caching : (Dont cache when not required).
a=x+y*0.5;
z=a+(b*c)/c;
In the above example you don’t  need to cache 'a' you can directly calculate. 
z=(x+y*0.5)+(b*c)/c;

2  Cache whenever you are repeating the values in calculation:
bottomLayerWidth = 5 * ((x/2)*(.5*y));
topLayerWidth = 2 * ((x/2)*(.5*y));
textLayerWidth = (4 + z) * ((x/2)*(.5*y));
statusLayerWidth = (2 + r) * ((x/2)*(.5*y));
Should be changed to so that repeated calculation would be reduced
var changeVal = ((x/2)*(.5*y));
bottomLayerWidth = 5 * changeVal;
topLayerWidth = 2 * changeVal;
textLayerWidth = (4 + z) * changeVal;
statusLayerWidth = (2 + r) * changeVal;
3.      When you are writing a recursive algorithm cache the values whenever require so that you dont have to calculate it again. refer(http://memoizationinjavascript.blogspot.in/)

4.      If you have a series of If-Then-Else statements, you should try your best to organize them from most likely to least likely. This way the program doesn't have to traverse all the unlikely conditions to get to the likely ones, which will be called more often.

5.      Don’t use nested loops if not required.

6.      Use ‘switch’ instead of lengthy ‘if-then-else’ statements.

7.      Avoid Global variable.

8.      Proper scoping of objects would reduce the data collision

9.      Hide the information not required and expose whatever is required.

10.  Encode and decode when your are using ajax request which would load fast.

11.  Avoid dynamic loading of content.

12.  Use lazy loading whenever required.Load the files when dom is loaded completely so that it would not stop user from viewing the web page.

13.  Minimise the use of images .Sprite your images so that it would be loaded fast.

14.  Avoid ajax interactionand try to store in browser local storage so that it would increase the performance. Use ajax whenever required like pull some data from data base for a particular id.

15.  Modularise your javascript code.

16.  Avoid use of libraries(jquery,angular..) when you dont have much of algorithm to be written. They would reduce the time to code but in turn add an extra sec to load the file.

17.  Unbind events when not in use.

18.  Use ‘mouseup’ instead of ‘click’. Remember that user interaction via the mouse or keyboard fires several events in a specific order. It is useful to remember the order in which these events fire so you can squeeze in your functionality before anything else gets handled, including native browser event handlers.

19.  Use currrying whenever required. Function would be partially executed.

20.  Use chaining                                                                                                                                      
var people = helper.getPeople(); 
var bob = people.find("bob");
var email = bob.getEmail(); 
helper.getPeople().find("bob").getEmail();

21.  Save bytes by using Minification.

22.  Avoid biniding events to body or document. attach events to document or body only when added dynamically.

23.  Avoid Function Inlining. Function Inlining helps to eliminate call costs, and replaces a function call with the body of the called function. In JavaScript, performing a function call is an expensive operation because it takes several preparatory steps to perform: allocating space for parameters, copying the parameters, and resolving the function name.

24.  Don’t misuse for-in Because the “for-in” loop requires the script engine to build a list of all the enumerable properties, coding inside for loop does not modify the array. It iterates pre-compute the length of the array into a variable len inside for loop scope.
\Use the attributes properly when and where required. for example atl attribute is very much required in img tag if the image crashe to load atleast you can display what image is that by adding content to alt tag.
a

26.  Avoid using try-catch-finally. Whenever the catch clause is executed, where the caught exception object is assigned to a variable, “try-catch-finally” creates a new variable in the current scope at runtime. A number of browsers do not handle this process efficiently because the variable is created and destroyed at runtime. Avoid it!


Memoisation in javascript

Memoization is an optimization technique used primarily to speed up computer programs by keeping the results of expensive function calls and returning the cached result when the same inputs occur again. Memoization has also been used in other contexts (and for purposes other than speed gains), such as in simple mutually recursive descent parsing in a general top-down parsing algorithm that accommodates ambiguity and left recursion in polynomial time and space. Although related to caching, memoization refers to a specific case of this optimization, distinguishing it from forms of caching such as buffering or page replacement. In the context of some logic programming languages, memoization is also known as tabling.

Caching is a useful general technique that sometimes makes programs run faster. It does this by exchanging space for time: Caching tries to save previously computed results in an attempt to reuse them later rather than recomputing them.
Caching is useful in all kinds of situations, including, almost any kind of searching (cache the results of the search so that you can skip it next time), HTML generation (cache the results of the generation process so that you don't have to generate the page next time), and numeric computation (cache the results of the computation).

Lets take an example of recursive function, Fibonacci series
In the following example, the original Fibonacci function is rewritten to include memoization. In the example, a self-executing anonymous function returns an inner function, inner(), which is used as the Fibonacci function. When inner() is returned, its closure allows it to continue to access the “memo” object, which stores all of its previous results. Each time inner() is executed, it first checks to see if a result exists for the current value of “n”. If it does, then the cached value is returned. Otherwise, the original Fibonacci code is executed. Note that “memo” is defined outside of inner() so that it can retain its value over multiple function calls.

var fibonacci = (function() {
  var memo = {};
  function inner(n) {
    var value;
    if (n in memo) {
      value = memo[n];
    }
else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = inner(n - 1) + inner(n - 2);
      memo[n] = value;
   }
    return value;
  }
  return inner;
})();

There is of course a tradeoff involved in remembering values. It is faster to find a particular value, but it takes more memory space to store all of them. You should usually define functions to remember values only if the total number of different values that will be produced is comparatively small, or the expense of recomputing them is very great.



Reference :http://addyosmani.com/blog/faster-javascript-memoization/

Object oriented javascript

Object-oriented programming (OOP) is a programming paradigm that uses abstraction to create models based on the real world. OOP uses several techniques from previously established paradigms, including modularitypolymorphism, and encapsulation.OOP promotes greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. Because OOP strongly emphasizes modularity, object-oriented code is simpler to develop and easier to understand later on. Object-oriented code promotes more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods. 



Object: Every component in javascript is considered to be a object including the data types and function. Objects can be created either by object literal or constructor function.
lets say, 
         var person = {}
            or  
       var Person = new object() 
            or
       var Person = fuanction(name){ this.name=name;}

Namespace: This is like a container which contains all the data and functionality under a specific name. whatever object is created in javscript will be placed in global space unless we have specified the scope for it to exist. We can create a namespace as below.

            var application= application || {}

Here application would be created if it doesnt exists if exists existing one would be used. Namespace is very important or else we may end up with namspace collision.


Class:
 A class is a template definition of an object's properties and methods. We can create a class as below in javascript.

function Newclass(){

}



Inheritance : Before getting into inheritance let me explain a bit about protoype and how constructor behaves after overriding. We all know prototype is property of an object. Let say we have a Employee class

function Employee(name){this.name=name;}

Employee.prototype = {salary:'',grade:''}

Employee e1=new Employee(backend);


e1.constructor would give you Employee. Now check for e1.constructor.prototype.constructor which will give Employee which is actually not right. Now let me override the prototype.

Employee.prototype = {branch:'xx'};

Now if you try e1.branch you will get "undefined".Let me create a new instance say
Employee e2=new Employee(accountant); now if i try calling branch e2.branch it would give me xx and if I try calling e2.salary it says not a function. The prototype chain is live with the exception of when you completely replace the prototype object. So when you override its good to set the constructor property. In the below example I have a base class and child which wud inherit the common characters. The child class can be added by its own required properties.

function Parent(){
this.name=name;
}

function child(){

}
Child.prototype = new Parent();
Child.prototype.constructor = Child;


Encapsulation : 

A method of bundling the data and methods that use the data.Information hiding is a common feature in other languages often as private and protected methods/properties. Even though you dont have private publich protected methods like java/.net we can  simulate something like this on JavaScript. when you create a member data in a function it becomes a private member.  we can create objects with similar functionalities,you encapsulate the main functionalities in a Function and you use that Function’s constructor to create the objects. This is the essence of encapsulation


Polymorphism :

The programmer does not have to know the exact type of the object in advance, and so the exact behaviour is determined at run-time. This is what we call late binding or dynamic binding. Polymorphism can be implemented by  creating two functions with same name with difference in arguments. we can invoke the function by checking the argument  as shown below.

function fundTransfer(asianfund ,obj){
  this.fund=asianfund;
  alert(this.fund);

}

function fundTransfer(){
   alert('domestic');
}

function f(obj5,obj) {
    if(arguments.length == 2){
        return fundTransfer(obj5,obj);
    }
    else{
        return fundTransfer(obj5);
     
    }
};
f('asian','international');

Thursday, May 1, 2014

Image optimisation

Are you building an online store? Then you need to take care of your image while coding to render your webfaster to have a scuccesful ecommerce buisness. Images often take lot of time to be downloaded and occupy lot of visual space on the page, so optimisation of images play a major role in rendering page very fast. If the images are handled properly in the page the client side banwidth would be less and you can render your useful content fast. Now lets start our discussion on how to handle image to make browser download and render fast.

First thing before using image we should think whether image is really required? Can we replace image by css3 effects or using webfonts or css polygon. Eliminate wherever image is not required. Then cut down the possiblity of using image by alternative techniques like using webfont, css3 effects and css polygons. Css3 features like gradient shadows zoom level can provide alternate for image. Use of css polygons cuts down the usage of polygon like icon images used on pages.


Be careful while choosing the type of image as it is important to choose right type of image.

JPEG (or .jpg) images are standard image of the Internet. JPEG images are able to be compressed considerably, which results in quality images with small file sizes.
GIFs (.gif) are lower quality images than JPEGs and are used for more simple images such as icons and decorative images. GIFs also support animation. Regarding image optimization, it's great to use GIFs for the plain and simple images on a webpage.
PNG images are becoming more popular as an alternative to GIFs. PNGs support many more colors than GIFs, and they don't degrade over time with re-saves like JPEGs. Even though the PNG file type is starting to be used more, the file sizes can still be much larger than what you would find with JPEG images. So use JPEG in common and for simple small and animation images use GIFs and for tranperant images use PNGs.

Consider using alt in tags as they are altenative for image and use proper keyword for alt as it adds SEO value . When you hover image you will find the keyword which adds to SEO so consider the keyword while using it.


Use sprite image while you have lots of icons and small images in your web page.


Lazy loading of images filter defers loading of images until they become visible in the client's viewport or the page's onload event fires. This avoids blocking the download of other critical resources necessary for rendering the above the fold section of the page. You can do this by adding a data-attribute in img tag which would be the actual image and use a gif(loading) url in the src of th image tag . onload replace src by data-attribute.


While in design phase you can considering using pagination so that it wont be a high load for page to load all image at one set for ecommerce sites. Pagination you divide images into different pages and load image required for the current page. Which would improve page load.