Javascript reference object by an identifier or reference it directly? - javascript

I am creating quite many objects in Javascript, which I need to be able to reference to retrieve later, for example through an array. Now I am wondering how to save the object reference in the array.
The objects will interract with an external library, which can function either with object IDs or the object itself. I know Javascript treats object variables like pointers and not object copies, so is it safe to reference the objects directly ?
At first I was thinking "if I save the IDs of the objects, that would keep memory usage low", but is this true ? How much memory does an object variable* consume versus an integer variable ?
*the pointer to the object, not the object data
Also, if saving the objects directly is the way to go, is it ok to use array.push() to add the new object to the array ? Is array.push() creating a copy or does it work like a variable ?

Yes, you can reference the objects directly. If you really care about memory usage, I'd say the way of passing the ids will use more memory since you'll have to maintain another set of mappings.
Passing the objects directly will let the JavaScript engine to work directly with the object references. That's not affecting the memory usage, as long you don't to any cloning.

I believe the relevant question is weather or not saving an integer and using that as an identifier later is more effective than saving a reference to the object.
I'd go with the reference in an array. the size of a reference vs a number is going to be negligible.

Related

hasOwnProperty and object's properties access

I have very simple question.Is there any performance relation about accessing object's properties like object[property] and the number of properties ?? Is there some internal loop or something , same question about hasOwnProperty - any loops or just direct access like array[index] ??
JavaScript is a dynamic programming language: properties can be added to, and deleted from, objects on the fly. This means an object's properties are likely to change. Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk. In these languages, instance variables are located at fixed offsets determined by the compiler due to the fixed object layout defined by the object's class. Access is simply a matter of a memory load or store, often requiring only a single instruction.
use V8 (JavaScript engine) for better performance.

Binding Two Variables Together

qpo.activeGame.teams.blue
qpo.blue
Above are two references/identifiers. I create an object and have the first identifier (qpo.activeGame.teams.blue) point to it. Then, I want to have the second identifier (qpo.blue) point to the same object (which will change, and both identifiers need to keep pointing to the newest version of that object.)
Do I achieve this like this?
qpo.blue = qpo.activeGame.teams.blue
Or, is it more complicated?
I apologize for my lack of a computer science background. (Is data binding even the right term for this?)
You cannot cause two variables to become "married" so that an assignment to one is effectively an assignment to the other. (There's one weirdness that could possibly be construed as that situation, but it's not something you'd ever do in practice.)
However, if two variables (or object properties) refer to the same object, then changes to the constituent properties and sub-properties of that object will be visible via either reference. That's because a reference to an object is, in fact, just a reference. Two variables sharing the same reference value both refer to the same single object.

Ensuring object can be garbage collected

My node/javascript program receives lots of messages.
Each time a message is received I create a new object, passing it message content.
Within the new objects constructor, the object does a bunch of stuff, including some mongo operations with callbacks.
When the operations that are performed within the object constructor are complete, the object is no longer needed or wanted.
After some experiments involving complexity (i.e. storage of the object in an array element or as a property of a 'master' object and then deleting it, I tried the simple approach.
var x = new DisposableObject(message);
delete x;
This seems to work fine. There may be many instances of DisposableObject in existence at any time. DisposableObject is created and does everything expected of it in tests.
I am assuming that when I delete 'x' that this does not affect the object itself, just the reference to it that is contained in 'x'. The objects callbacks occur and all is good.
So four questions:
Will this simple mechanism allow the garbage collector (node/V8) to get rid of the object?
Is there some awful trap door awaiting my code because I am doing this?
Is there any issue with multiple instances of DisposableObject floating around waiting for callbacks when there is no active reference left to them in my program?
Is there a better way to create the objects, then make sure they can be garbage collected after all their operations are completed?
Javascript uses a nongenerational mark-and-sweep garbage collector, in javascript objects are automatically garbage collected when they are no longer needed , so you need not worry about garbage collection.
but you have to keep these points in mind (from this answer):
what you are trying with delete does not really delete an object, delete is only effective on an object's properties. It has no effect on variable or function names., Use delete statements whenever you create an object using a new statement, pair it with a delete statement. This ensures that all of the memory associated with the object, including its property name, is available for garbage collection. The delete statement is discussed more in “Freeing Objects.”
Use the var keyword. Any variable created without the var keyword is created at the global scope and is never eligible for garbage collection, presenting the opportunity for a memory leak.
In case of global variables, Global variables are never disposed of by the GC in the sense that a global variable will always exist. Setting it to null will allow the memory that it references to be collected. the memory used by the object will be eligible for collection. but The variable still exists though, and it simply references null(some more here)

Is it possible to store an object with functions (proto) as a cookie?

I have an object called Game, which has properties name, number, teams, etc. Many of its properties are objects themselves: teams is a list of Team objects.
All of these objects have functions defined using proto (not sure of the actual terminology), for example
Game.prototype.getName() {
eturn this.name;
}
is one of the game's functions. I want to be able to store the game, along with its functions, as a cookie. I should be able to load this cookie later on and get my original Game object.
JSON.stringify doesn't preserve the functions, just the properties of the Game. Is there anyway I can 'stringify' an entire object including its JavaScript functions? I'm using AngularJS if that matters.
I think you should only serialize data, not the behaviour. Once retrieving your data back from JSON you could instanciate relevant Objects with that data, thus giving them back their behaviour.

Why is it faster to access the DOM through a cached variable?

I am trying to improve my knowledge of javascript and while searching for some "best practices", someone pointed out to me that it is faster to cache the DOM document and then access it through that var instead of accessing the document object directly.
You can see the results here, on an edit I made on jsperf: http://jsperf.com/jquery-document-cached-vs-uncached/3 (edit: the title holds "jsquery" because that was the original test, my edit contains vanilla javascript, the framework makes no difference)
This really makes me curious. Basically I am introducing a new variable into the equation, how can that make things faster instead of slower?
As far as I know, "print a" should be better than "b = a; print b" (figure of speach)
What's different in this case?
document is not like an ordinary Javascript variable. There's no telling what odd magic is happening under the covers when accessing its attributes, especially the DOM, which may be created on demand from internal browser structures.
I believe I found an explanation here (the emphasis on the last part is mine):
Store pointer references to in-browser objects. Use this technique to
reduce DOM traversal trips by storing references to browser objects
during instantiation for later usage. For example, if you are not
expecting your DOM to change you should store a reference to DOM or
jQuery objects you are going to use when your page is created; if you
are building a DOM structure such as a dialog window, make sure you
store a few handy reference to DOM objects inside it during
instantiation, so you dont need to find the same DOM object over an
over again when a user clicks on something or drags the dialog
window.If you haven’t stored a reference to a DOM object, and you need
to iterate inside a function, you can create a local variable
containing a reference to that DOM object, this will considerably
speed up the iteration as the local variable is stored in the most
accessible part of the stack.
So, if I understand correctly, caching the DOM in a local variable makes it easier to access in the memory stack, therefore increasing the speed of execution.

Categories

Resources