I have been working on web project for past 4 months. To optimise the code performance we have used a pattern. My doubt is, does it actually boost performance or not?
when ever we have to use this
object we assign it to a local variable, and use that.
function someFunction()
{
var thisObject = this;
//use thisObject in all following the code.
}
the assumption here is that, assigning this
object to a local stack variable will boost the performance.
I have not seen this type of coding anywhere so doubt if it is of no use.
EDIT: I know that assigning this object to local variable is done for preserving object, but that is not our case.
As with ALL performance questions, they should be examined by actually measuring the performance. In a rather simple test case (your actual code might vary some), I find mixed results across the browsers:
Chrome and Firefox don't differ very much between the two tests, but the slight difference is in opposite directions between the two. IE9 shows the test using a saved copy of
this
which I calledself
to be significantly slower.Without a significant and consistent performance difference in Chrome and Firefox and IE9 showing the
this
test case to be substantially faster, I think you can conclude that the design pattern you asked about is not delivering a consistent performance boost across browsers.In my code, I save a copy of
this
to another variable only when I need it for a consistent reference to the original object inside of inline event handlers, callbacks or methods wherethis
has been set to something else. In other words, I only apply this design pattern when needed.In a previous discussion of this design pattern here on SO, it was concluded that some libraries use this design pattern in order to allow additional minimization because
this
cannot be minified below the four characters that it takes up, but assigning it to a locally variable can be minified to a single character variable name.Even when this kind of optimization has an (positive) effect, it is very likely to depend on the interpreter.
An other release may revert the results.
However, in the end you should measure, not guess.
While this is a common practice in Javascript it's not done for performance reasons. The saving of the
this
object in another named local is usually done to preserve the value ofthis
across callbacks which are defined within the function.Whether or not
thisObject === this
evaluates to true will depend on how it's called