Reputation: 50602
Is either of these patterns more or less efficient than the other?
Pattern 1:
var jso = new Class({
initialize: function () {
// code
},
hiliteField: function () {
// code
}
});
Pattern 2:
var jso = new Class({
initialize: function () {
this.hiliteField = hiliteField.bind(this);
// code
}
});
var hiliteField = function () {
// code
}
Upvotes: 0
Views: 200
Reputation: 1862
Pattern 2 will use more memory! It's the basics of prototypal inheritance
Why? In Pattern 1 every instance of jso
will reference jsoInstanceX.hiliteField
to jso.prototype.hiliteField
. Read: hiliteField
will not be a copy, it will only exist in jso.prototype
.
In Pattern 2 you create a function wrapper each time you assign hiliteField.bind(this);
. The additional memory is not much, but it's also slower, especially with impact on Class initialization.
Upvotes: 1
Reputation: 26165
Having multiple methods that are external to the class and up the scope chain, as opposed to behind the class as 'namespaced' methods can't be better, imo.
Don't like pattern #2 for several reasons:
That being said, from a memory standpoint - just do a test but I would say, pattern 1 is likely to have a smaller overhead because it's defined once on the prototype and not in every instance individually.
Upvotes: 1