Reputation: 5201
Im making a snake game in javascript and im creating the objects and gameloops inside the window.onload function.
window.onload = function() { ... Code ... };
Now Im wondering over the objects Im creating inside the function scope are efficiently used? What is the difference between using these two kinds of declarations?
1:
var Snake = {
x: null,
y: null,
initialize: function(x, y) { this.x = x; this.y = y },
position: [x, y],
move: function(x, y) { ... Code ... }
}
2:
function Snake(x, y) {
this.x = x;
this.y = y;
this.position = function() { return [this.x, this.y]; };
this.move = function(x, y) { ... Code ... };
}
Im currently using the 1: case and calling the objects from the scope of window.onload
function, for example it looks like this:
Snake.initialize(x, y);
while(some condition) {
Snake.move(x++, y);
}
and so on...
Is there a difference in memory allocation and is there some performance issues with one over the other?
Upvotes: 5
Views: 78
Reputation: 94429
The first method only creates one object using object literal notation, while the second method uses the constructor function method which can create several instances of the object.
For example method 2 allows:
var snake1 = new Snake(1,2);
var snake2 = new Snake(2,2);
//now I have two snakes, however method 1 would only ever have one copy of snake.
Using method 1 will provide one global instance of the Snake object for the entire game.
Creating multiple instances of an object is going to require more resources, however in this case it may not be noticeable. If you only need one snake within your game use method one, if you plan on having multiple snakes, method2 is the right approach. I wouldn't worry about performance or resource usage until it becomes an issue within your game.
Article on Constructor Function
Upvotes: 3
Reputation: 20159
If there's only one Snake
in your whole program (which is very likely), then the first approach is probably the easiest solution. You probably won't notice the difference in efficiency between the two.
If there are multiple Snake
s in your program (e.g. you're making a multiplayer), then the first approach won't suffice. The Snake
object in the first approach compares to a singleton in an OOP language, meaning that you only have one in your whole program. The second approach is a constructor (which compares to a class), meaning that you can construct multiple Snake
instances with different properties.
You could still improve that second approach by storing the position
and move
methods on the Snake.prototype
instead of creating new functions in every constructor call. It might not matter that much for efficiency, but you'll get fancy prototype-based inheritance allowing you to make other constructors (classes) inheriting from Snake
.
Upvotes: 0