Omar Abid
Omar Abid

Reputation: 15976

jQuery functions performance

I was building a large web script with jquery. It does various things and one of them is interacting with the DOM elements. I used a simple JavaScript function

function mymainclass() {

// declared variables here
this.var1 = new String
// Some functions
this.fn1 = function () { ... }

}

After that, I added other functions using the prototype function in JavaScript.

mymainclass.prototype.afn1 = function () {
...
}

I made a good progress using this methodology, finished writing around 300 lines before I read the Appendix C in "learning Jquery" book. It was about Javascript closures, and it recommended that I use jQuery fn function. So instead of adding functions by prototype I would use:

jQuery.fn.afn1 = function() {
....
return this;
}

I re-factored the whole code from scratch. I was happy because of the new usage

$('..').afn1('..','..',...);

which is much more better in coding; but when I was trying things in my new code, I noticed that it's much SLOWER than the old one. The old code speed is 50.56ms in total compared to 488ms when the jQuery.fn was used.

I would appreciate any advice about the jQuery plug-ins methodology. I'm afraid that after going 4000 or 5000 lines in my script I find it quite slow and will be obliged to re-factor the code from scratch. What shall I do? Did you find the same issue?

I would also like to know how do you optimize a script so it runs quicker. I use FireBug to track the speed.

Upvotes: 1

Views: 210

Answers (1)

David Hellsing
David Hellsing

Reputation: 108500

Normally you'd want to use the jQuery plugin authoring when you are targeting DOM.

If you are familiar with the javascript prototype and writing more complex apps, it might be a good idea to write your code using native inheritance first, and then add a jQuery plugin to simplify DOM implementation.

Prototype is a fast and memory-effective way of extending your javascript code, since every instance inherits the same prototype methods without the need for duplicates.

I tend to write the app in a native environment and then add a plugin if needed:

myClass = function(elem) {
    this.elem = elem;
}

myClass.prototype = {
    myMethod: function() {
        // do stuff
        this.elem.className = 'foo';
    }
}

$.fn.myClass = function() {
    return this.each(function() {
        var instance = new myClass(this);
        instance.myMethod();
    }
};

Now you can use this class i two ways:

$('#elem').myClass();

or:

var id = document.getElementById('elem');
var instance = new myClass(id);
instance.myMethod();

Upvotes: 1

Related Questions