📜 ⬆️ ⬇️

Firebug: Part 4 - profiling

How good code will help avoid debugging in debugger, so it will also help you never apply the skills learned in this article.
If on your site your browser “dies” from being overloaded by javascript, then you just need to read it (and apply it too).

All cycle: Console , Commands , Debugging , Profiling


')
Today we will write a little javascript and optimize it, because this is our goal.
All the action will take place on the main habrabra .
Let's start small, collect all the links on the page:
links = $$( 'a' );


They will be the object of our bullying.
Now we will create two functions that will add and remove the “hidden” class, which is used in the habré for the intended purpose:
hide = function (el) {el.addClass( 'hidden' );}
show = function (el) {el.removeClass( 'hidden' );}


And now we will write a function that will hide and show all links on the page:
js = function () {
for ( var n=0; n<links.length; n++) {
hide(links[n]);
show(links[n]);
}
}



And run the profiler:
console.profile( 'js' );
js();
console.profileEnd();



Let's wait a bit, and get the result, which shows that the function called by removeClass () and getComputedStyle () are executed the longest in the function we called. The main reason for this is 401 calls to each of them.

Now let's try the second way - let's call the $ each embedded in mootools:
each = function () {
$each(links, function (link) {
hide(link);
show(link);
})
}



And see the result:
console.profile( 'each' );
each();
console.profileEnd();



There is a gain (as much as 2ms), but we have not got rid of the main “brake”.

And remember that the functions addClass () and removeClass () can be called on an array of elements:
mass = function () {
hide(links);
show(links);
}


console.profile( 'mass' );
mass();
console.profileEnd();




And now, after all we have seen, we realized that there is no big difference. And it's time to think about whether we need to hide, and then show the 401 link?

The article is based on the blog Michael Sync .

* This source code was highlighted with Source Code Highlighter .

PS still sometimes you can find a lot of nonsense in the code because of which it will be slow to execute.

Source: https://habr.com/ru/post/51113/


All Articles