Hello friends, today I am going to show a very very important testing i.e performance testing of a javascript function.Why will we do this testing is because to calculate the perfomance of the javascript application.Every body knows that now a days the popularity of Javascript applications, so it is mandatory to calculate the performance of the application. Performance testing is one type of Unit testing.
There are various ways to do the performance testing, such as
- Using Date and Time method :
This is a very simple process to calculate the performance of javascript functions. What will we do is just we need to use getTime() just before and just after of the calling place of the javascript function by assign into two variables. After this the difference between the two times will be time taken by the execution of the function.
Following example will explain you to understand the complete logic.
/*=========== Code To Test Performance ============*/
function funTest(){
for (i = 0; i < 10; ++i) {
alert(i);
}
alert("hi");
}
var start = new Date().getTime();
funTest();
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
/*===============================================*/
In the above example we just called a function in between two time function and calculated the difference between the two times.
Note :
The result we will get here in mili sec format.
- Performance.now() API :
By using this also we can calculate the performance of the execution, but this is more accurate then the above process.
In this process we will do same as above process, i.e we will call and assign the performance.now() to two variables just before and after of the calling place of the function (whose performance we will test). Then the difference between the values of two variables will give the time taken by the execution of the function that is nothing but the performance of the function.
Following example shows the details of the process.
/*=========== Code To Test Performance ============*/
function funTest(){
for (i = 0; i < 10; ++i) {
alert(i);
}
alert("hi");
}
var a = performance.now();
funTest();
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
/*===============================================*/
Note :The result we will get here in mili sec format.
No comments:
Post a Comment