Discussion Locked

A custom JavaScript Collection Object

0 helpful
4 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
Is Phillip on the money, or have you found a better way to create a custom JavaScript Collection Object? Share your experience with creating custom JavaScript Collection Objects with your peers.

4 replies

by jay eckles

Any chance you could post a link to the article to which you are referring? I missed it and can't seem to find it on the site.

by joshsg77

I would just use Object and forget about index values, but to make this implementation efficient, set the references to the member functions outisde of the constructor, using the prototype property of the constructor function. Doing this saves a tonof memory! I ran the following code with cscript.exe in windows and observed the memory usage for it. When calling runit(1), which assigns the methods the way this article does, it takes a long time and 42 meg of memory, with runit(2), it runs to about 9 meg in a few seconds:

function Collection1() {

this.Add = function() {
return "Hello";
}

this.Remove = function() {
return "Gone!";
}

}

function Collection2() {

}

Collection2.prototype.Add = function() {
return "Hello";
}

Collection2.prototype.Remove = function() {
return "Gone!";
}

function runit(num) {
var cols = [];

for (var i = 0; i < 30000; i++) {
cols.push(new this["Collection" + num]());
}
}

// Set 1 or 2 below to test
runit(1);

There is an article on my site about common javascript coding errors and better practices, please check it out:

http://www.ultravioletconsulting.com/technical/javascript.html

-Josh

by joshsg77

I would just use Object and forget about index values, but to make this implementation efficient, set the references to the member functions outisde of the constructor, using the prototype property of the constructor function. Doing this saves a tonof memory! I ran the following code with cscript.exe in windows and observed the memory usage for it. When calling runit(1), which assigns the methods the way this article does, it takes a long time and 42 meg of memory, with runit(2), it runs to about 9 meg in a few seconds:
function Collection1() {

this.Add = function() {
return "Hello";
}

this.Remove = function() {
return "Gone!";
}

}

function Collection2() {

}

Collection2.prototype.Add = function() {
return"Hello";
}

Collection2.prototype.Remove = function() {
return "Gone!";
}

function runit(num) {
var cols = [];

for (var i = 0; i < 30000; i++) {
cols.push(new this["Collection" + num]());
}
}

// Set 1 or 2 below to test
runit(1);

There is an article on my site about common javascript coding errors and better practices, please check it out:

http://www.ultravioletconsulting.com/technical/javascript.html

-Josh

This discussion is closed to new replies.