JavaScript: Using closures and prototype to write resource efficient programs

In JavaScript, everything is an object, which includes operators, numbers and arrays. One of the most important aspects in javascript is the treatment of closures:
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
Any dynamically typed language, that is languages wherein variable and parameter types are inferred at runtime, have to be garbage collected, owing to finite memory resources.

ECMAScript uses automatic garbage collection. The specification does not define the details, leaving that to the implementers to sort out, and some implementations are known to give a very low priority to their garbage collection operations. But the general idea is that if an object becomes un-referable (by having no remaining references to it left accessible to executing code) it becomes available for garbage collection and will at some future point be destroyed and any resources it is consuming freed and returned to the system for re-use.
With increasing operation complexity and numbers of object instances for any given web-application, it is paramount to write code with garbage collection in mind.

Secondly javascript has expanded considerably with definitions embedded in strings or comments, such as strict and Googles closure compiler, which allows to increase performance by defining the types of the parameters and objects in the comment in conformity to a certain scheme, which may look as follows:



Namespaces in Javascript can be resolved through the with keyword, which takes an Object as a parameter and then sets the scope to this Object within the statement. The following example highlights scope intricacies:



The output of the example above is:


undefined
check
10
10
10
20
y
undefined
10 undefined
10 "I'm global" "I'm global"
undefined
check
10
10
10
20
y
undefined
10 undefined
10 "I'm global" "I'm global"

exmpl
"I'm global"
y
exmpl
<-undefined


 function exmpl(){ var y = "check"; y = 10; console.log(y) }; exmpl();

The following examples are from this excellent assay on Javascript closures:

Here is a short to-do list for writing resource efficient code:

Avoid closure generation in cases where Objects are repetedly instanced. For instance use:


Use prototype.attributes and methods instead of closures in defined within the Object




Lastly, some final aspects. Avoid unnecessary function calls. Clear up variables not used (delete). Always use var. Be aware of the internal cleanup routines of more complex Objects such as SVG and canvas. (Javascript does not have destructors)

Keep in mind that javascript is generally not implemented in such a way that it performs efficiently binary operations. Store initialization values etc, in Arrays if used throughout the program.
LihatTutupKomentar