Painting with The HTML5 Canvas :A small presentation.

What is a Canvas ?

Think of your HTML5 canvas as a simple drawing surface that provides some powerful drawing tools. This canvas
might be used on an html page for immediate display, but also behind-the-scene to prepare some graphics for later use.
The drawing tools are provided through a Context, and most web Browsers offers two (exlusive) ways to draw
on a Canvas : WebGL and the Context2D.
WebGL is a very efficient but also very complex context, meant for demanding 2D or 3D graphics.
This presentation will focus on Context2D, a context meant for 2D drawing only, way simpler than webGL , and
powerful enough for most drawing tasks .
Boiler Plate Code to get a Context2D in Javascript :
In your Html file, add a canvas, give him a size (width, height), in pixels, and an id :

<canvas width=640 height=480 id='myCanvas'> </canvas >
// do not copy paste this html code but re-write it (issue with the < @gt; and html)

Then in your Javascript script, retrieve the HTML5 canvas element, and get its context2D with :

What a Canvas is NOT !

There’s a common misunderstanding of the canvas, especially from the ones having a strong Html background, that is
to see the canvas as a classical html container, just like, say, a
div, in which you would basically add/remove some
visual elements in pretty much the same way you do it in regular hmtl.
But this is completely wrong : when you draw, you actually only change the values of some pixels within your
graphic card, and that’s all. No ‘scene graph’ is built, meaning the canvas has no memory of what happened before : you
cannot query a previously inserted element to change it, remove it, make it draggable, or what-not.
Hence any logic that goes beyond drawing, must be done by yourself (or by an external library of course).
Rq : Those who likes to build scene as a way of drawing (building step-by-step some queriable objects) should have
a look either at an canvas helper library (createJS, fabricJS, … ) or have a look at the SVG format/Object.

Mind the current status

Using the Context2D is always done in two steps : you 1) first setup the (fill or stroke) color, the width of the line, the font when
dealing with text, and any paramaters then 2) you draw a figure.
When you draw (fill or stroke), the current settings values at that point of time will get applied.
Let’s look again at the red rectangle example, that we’ll visually improve a bit by adding a shadow :

You should notice here that the final draw call (fillRect) did not change : what did change is the status of the context by
the time of that call -here it is set to : red fill and black shadow.
Principle is that all the changes you make to your context are ‘sticky’ – remains active until you discard them – which is
why the Context2D is called a ‘state machine’ -a machine that internaly handle some state variables for you-.
!! it can lead to tricky bugs if you don’t keep this idea always close to your mind. !!
Now you may wonder how you’ll keep some order in your drawing code : what if i want to draw one thing with a shadow,
and another with no shadow ?
Hopefully we have a life-saver here, which is the save/restore principle : let’s see it in action :

Here, after that code has run, we have a red shadowed rectangle drawn, and the current status of the context is exactly
what it was before (not red – no shadow).
Any time you wonder if a change you make to the context will affect other drawings you make, do
not wonder a second, and save (before) / restore (after), so you can be sure no specific settings will be applied on
other objects.

Two ways to draw

The Context2D offers two ways of drawing :
• Some drawing commands are immediate, meaning they will use the current status of the context to immediately
change the pixel colors . They are used for most common simple cases (see the above fillRect example).
• Some drawing commands are retained : they do not affect the pixels until you perform a stroke() or a fill(). They
are used in more complex cases, when drawing shapes built out of bezier curves, lines, …

Draw directly

The immediate commands of the Context2D are :
• fillRect / strokeRect : draws either the (filled) rect or just its outline.
• fillText / strokeText : draws either the text or just the text outline.
• clearRect : erase a part of the canvas.
• drawImage : used to draw an (or part of an) Image or canvas on current canvas.
• createImageData / getImageData / putImageData : (advanced) used to get/set the raw values of pixels.
• toDataURL : used to create an Image out of the Canvas.

Draw complex figures

The Context2D also offers some ‘retained’ commands that allows to draw more complex geometry. You can build
those geometry out of : lines, rect, arc (= part of circles), bezier curves, quadratic bezier curves, and arcTo.
The key thing to remember here is that you should always start a retained draw by beginPath, then build your
geometry step by step. Rq that nothing is drawn until you choose to stroke the outline or fill the whole geometry. You can
use closePath to automatcally link (by a line) the last point and the first point of the geometry.
You remember Context2D is a state machine, right ? So think of this way of drawing just like you woud do with a pen, which
‘remebers’ where it stands. Questions are : Where is the pen right now ? Where do i go from there ?
Here are the various retained commands of the Context2D :
• beginPath : start a new path. required for every new draw.
• closePath : Links the last built point to the first point by a line. Only if you need it.
• moveTo : unlift the pen, then set it at the provided point.
• lineTo : links last point to the provided point by a line.
• rect : adds a rect path to the current path. ! Rq that it does not draw immediatley like fillRect or strokeRect !
• arc : adds a (part of) circle to the current path.
• bezierCurveTo, quadraticCurveTo, arcTo : adds the corresponding mathematical curve to the path. All those curves
have a ‘smooth’ aspect.
A small example, a blue triangle :

Let’s fill those geometry nicely

You might stroke or fill with a single color, sure. To define a color, you have various ways :
• an html color string : ‘yellow’, ‘red’, …
• a rgb string : ‘rgb( 23, 150, 80)’
• a hsl string ‘hsl( 39, 75%, 75%)’ . Hsl is very handy to quickly create a coeherent palette.
• an hexa rgb string : ‘#FFE118′. This is the fastest way, if performances matters.
You can use a color picker (online or from your graphic editor) to find the right color.

BUT what about pouring even more colors ? The canvas provide two gradients for your viewing pleasure : a linear
gradient, and a radial one. To build a gradient, you must choose the part of the screen you’ll paint, then you define some
‘color stops’ : the color steps by which the gradient goes.

BUT you can also use some kind of (simple) texturing, and have a pattern repeated with the createPattern method. Very usefull
to build a wall out of a brick photo. Notice that the pattern might be built out of a canvas, so you can build a small off-screen
canvas, draw one star on it with various colors on it, then create a pattern out of that canvas and fill the on-screen canvas with
that pattern !

Transform / Clip / Go Composite

Well now you drew some nice things using lines, bezier curves, and such, but you’d like to draw all this twice as big : how ?
Hopefully you have transforms just for that : you can translate, scale, rotate your context at any time to re-use some
drawing code in another way and do some nice effects. Mind that rotation angle is in radian, not degrees.
A small example :

Another powerful feature is the globalCompositeOperation modes. They allow to change the way pixels are drawn, on a
per-pixel basis. You can use it for doing advanced masking with bitmaps. Use scenario are very specific, but they are very
quickly performed by most browsers. Notice that you can also define a blend mode, that will allow to do nice effects on colors
(the kind of effects high-end drawing software provide)
A scheme of the various composite modes is here :
It shows the output of drawing a new circle on an existing rect.

Last powerful feature is the clipping. You can define a part of the screen that will be the only part affected by all later drawings.
To define it, just create a path that defines the preserved area, and call clip ! Then do your drawings as usual.
You’ll most likely want to save/restore to avoid the clipping to remain permanent.
Small example :

documentation in Javascript

Javascript does not provide a built-in documentation tool : When one is searching for informations on how to use a class, a method or a property, he will have to dive into the code to find the relevant comments, which is time-consumming and might lead programmers to read the code rather than the documentation, thus favor implementation for specification and write code only compliant with the current version of the API. Another issue here is that if an API is provided minified, the documentation will be removed.

Another option is to use an online documentation site. Such documentation site can be generated automatically, with YUIDoc for instance. The issue here is that the help is not tied to the code, but rather an independant web site.

A pattern for functions.

Let me suggest a pattern i found usefull, that allows :

– keep the code and its help together.
– easy to use.
– standard.
– resistant to minification.

This way you can provide help even with a minified version of your API, meaning you share the functionnality but not the code : your secrets are safe ( :-) ).
The idea is to take advantage of the lexical scope of a nammed function declaration, and that a function is an object to write.
Help is a string that is defined on the function object prior to its definition. This way you can read it when browsing the code.
But more importantly, you can have a description of the function in the console by typing functionName.help .

Conclusion

The proposal i make here is still uncomplete : for instance, properties defined on the prototype can’t provide
for any help.
But the main idea seems interesting : with this pattern, accessing the documentation of an API -even if
it was minified- is just as simple as typing in the console ClassName.help or className.method.help. No need to have the code,
no need to browse the code or an online documentation. The programming experience gets closer to the one we can have with
high level languages/editors.

Let me know if it triggers some thoughts, do not hesitate to comment, and happy coding !

Why creating an object creates an issue.

We all know about the evil garbage collector of Javascript, a cruel monster that might at any moment freeze your game to recollect unused memory, and waste some frames or loose some inputs events, spoiling the game experience.
The fight against garbage creation must be led on several fronts : I’ll adress here the specific case of object creation using a constructor function, and in this article, i’ll present a way to recycle those object in a simple manner.For those who likes to know the end of the movie before it starts : The simple and classical pattern i expose here leads to X2 to X5 performance boost, and reduces game freeze.

using the new operator is equivalent, in Javascript, to create a new object : {}, and assigning it to the ‘this’ of the constructor function.

The constructor function (MyClass) will then perform intialisation and add some properties to the object. Memory will again be allocated for those properties.

When the object is no longer in use (‘goes out of scope’), its memory it is not recollected at once : rather it is marked for recollection, hence feeding the evil garbage collector. When, at some random point in time, memory is lacking, a large amount of memory is reclaimed all at once : garbage collection occurs, freezing the game for up to 10ms – a disaster-.

Let us see a very simple example :

// in the init of the game...
var someBadGuy = new BadGuy() ;
// later on during a fight...
if ( Hero.strength > someBadGuy.strength ) {
Hero.kills++;
someBadGuy = new BadGuy(); //create a new enemy to fight against
}

Here, when we create a second bad guy after defeating the first one, we overwrite the reference to the first guy (someBadGuy= new BadGuy()), so we have no more reference to the first guy : We created garbage.
Hence the first guy object is marked to be later recollected : this simple code is allready exhibiting a potential issue (in fact it created a performance issue in the future).

The performance hit due to object depends on two factors : the frequency of creation/disposal of objects, and the size of those objects.
Some sensitive cases might be :

Frantic games (no, i’m not talking about Super Crate Box :-) )

Games using a particle engine (for explosions, rainbows, …).

Games using 2D/3D physic engine(hence vectors computations).

But even in a slow-paced game, the recollection will randomly occur and make your character sometimes react oddly to, say, keystrokes, and hinder player’s experience.

Another thing worth noticing : Some (most?) game frameworks generates quite some garbage only to handle mouse moves or key strokes, and/or to handle object collisions, and/or use a class system that makes any class instance -even for simple classes- use quite some memory.
So before you even started to put some action, you can rest assured that the garbage collector will score in your game.
Still, this is not a reason to quit the fight.

The solution : let’s go to the pool

There is a much neater way to handle your objects : use a pool.

A pool is a stack of object that you put aside for your game :

When a new object is required, just take it from the pool then initialize it.

When you no longer use your object, throw it back in the pool.

If you need an object and the pool is empty, then -too bad- just use standard new() to get a new one.

So allocations happens less frequently, and recollection never happens (during the game).
Even better : if you determine the maximum number of objects your game might use, you can even pre-fill your pool with this number of objects, and you’ll never have to create or wait for recollection for this object.

// create a new bad guy like this :
var myBadGuy = new BadGuy( 100, 10, 'AK47', 100);
// later on you can use it like this :
if (myBadGuy.isAlive && myBadGuy.canShoot()) {
Hero.runAwayShouting('please do not use your '
+ myBadGuy.gun +' on me !!');
};

So now let’s get back to pooling : the thing you have to change to a true JS constructor function to enable pooling is to handle a call with no argumentsand make sure you setup your object just like a brand new one within the constructor :

This not a limitation, since even if you’re not pooling, handling undefined arguments :

Protect your function from calls to new() with a wrong number of arguments.

Ensures inner JS engine optimisations, since properties always have the same inner type (they never have the doomed ‘undefined’ value ).

It allows you to call the constructor with only the relevant parameters.

What you mustn’t do when pooling, though, is to add properties or methods on a created object, like with :

myBadGuy.isSmiling = true;

This, again, is not a limitation, since late object change is a bad practice : it breaks inner optimisations of the JS engine (The JS engine creates a cached backing class for your object : this cache is broken if you change the object on the go).
– Simple solution for this : pour all the stuff you need in your object in the first place -.

So let us now create our pool :

BadGuy.pool = []; // this one was hard.

(this code, as well as following code, has to be inserted
before the first object creation, but i don’t copy everything for clarity).

Now to get a new bad guy, we need another method that retrieves an object from the pool if one is available : pnew :

Notice that i set the myBadGuy var to null after disposal : this is to ensure we never reference twice the same object.
Here’s an example of what might occur if we do not pay attention :

var firstBadGuy = BadGuy.pnew(10); // get a guy, posX=10
firstBadGuy.pdispose(); // finally we don't need him...
// ... but keep the reference..
var secondBadGuy = BadGuy.pnew(50); // get another guy posX=50
// It is taken from the
// pool, and it is the latest
// pushed, so === to firstGuy
// so now we have two references to the same object.
// if we do :
firstBadGuy.posX = 200 ;
// we have for the second guy :
console.log( secondBadGuy.posX ); // --> output is 200, not 50 !!!

The issues that might be caused by multiple references might be a nightmare to detect and debug : each time you call pdispose(), ensure you don’t hold any reference to the disposed object.

So now, you must change all your new() calls to pnew(), and whenever an object is no longer in use, you must take care of pdisposing it and clearing any reference to it.

and then …

HURRA !!!!

At this point we have our pooling system, and the ugly garbage collector is defeated !!

or is he ?

Not quite, i am afraid : we have two concerns left.

Issue 1 : We still create some garbage.

When using push() and pop(), we do allocate/disallocate memory, so we still feed the monster with some crumb, so let us use an always-growing stack by handling the lenght separatly. You’ll see how in the final code.

Issue 2 : what about re-use ?

We obviously need a way to avoid re-writing the same code for each pooled class.
Let us define a setupPool function on the prototype of the Function object, so that all functions call get pooled easily.

As told earlier, i use an always-growing array/stack, so i handle its length separately in a poolSize property.

I added here the possibility to pre-fill the pool, so no object creation occurs even within the first seconds of the game.

I set, within the pool, to null the reference of the object we just grabbed to allow recollection in case it is not pdisposed afterwise, and just goes out of scope.

In case you have some disposal work to do, just set a dispose() method on your object, it will get called when pdispose is called. One reason to do so might be that the object’s properties themselves are pooled.

You might want to detect if you forget to pdispose some objects by counting all calls to pnew and to pdispose. At any moment you should have :
activeObjectsCount == pnewCount – (pdisposedCount – initialPoolSize)

So now victory is complete and all this was a very nice fight. Thank you for reading.

No ! Come On ! We want to know about the performance boost !

Ho, yes.

sure.

In fact this quite difficult to build a test that reflect an actual game sequence, where many object of different sizes have very different lifespan, and where ‘standard’ object ({}, [], strings, closures, functions, …) might be forgotten as garbage all along the way by many not-so-efficient game frameworks.
Another thing is that the performance measure won’t show us for how long the garbage collector froze the JS code during the tests. But i watched on FF/Chrome and we can see that garbage collection occurs often without pooling, and never when pooling (as expected).

Anyway i built a test in JSPerf that reflects *somehow* the performance gain you can expect from pooling.

So i consider that we have 4 different pooled objects, with different memory footprint (more realistic), and a given number of active object that i select randomly within those 4 classes.
We’ll create/dispose of them using three methods :

pre-filling the pool helps either a little or not at all.
Chrome sees a near X2 boost.
Firefox manages poorly memory, bust can be as fast as Chrome if helped : X5 boost.IE10 gets a X3.3 boost.
The ipad appreciates the pre-fill, and gets a X2 boost.Safari on mac OS, also enjoys pre-fill X2 boost.

Let me know if you experiment pooling in your game : i especially think here of games using intensively vector computation, where the speed boost should be tremendous.

So how do we find this normal vector N ?
Maths says that if (x,y) defines a vector V , its normal vector coordinates are (-y, x).
N, the vector normal to AB will hence have ( – ( yB – yA ) , ( xB – xA ) ) as coordinates.
But there is an annoying thing about this vector : it depends on AB length, which is not
what we want : we need to normalize this vector, i.e. have it to a standard length of 1, so when we later multiply this vector by w1/2, we get the right length vector added.

Vector normalisation is done by dividing the x and y of the vector by the vector length.
Since the length is found using phytagore’s theorem, that makes 2 squares, one square root, and finally 2 divides to find the normalized vector N :

It is almost the same case as before, except that we’ll have to draw a half-circle from A1 to A2, and from B2 to B1.
To draw a circle in a canvas, you have to use arc. If you look how it works, you’ll see that it expects a start angle, and an end angle.
The start angle will be the angle between AA1 and the horizontal line, computed using the Math.atan2 function :

var angle = Math.atan2( yA1 - yA, xA1 - xA);

Notice that javascript’s atan2 expects the y as the first argument, and x as the second.
The end angle is just the opposite of the start angle : it is equal to the start angle + PI.

Explosions, fire, snow, blood, dust, shining stars, bonuses… particles are a handy tool to add nice effects to your games.
Every game object that is loosely related to the game logic (– eye candy –) should be handled as particle, since it allows to have very light weight objects, and it allows the game engine to focus on its real tasks.

The fireworks demo, running smoothly with 1800 particles.

JSparkle is a Particle engine that is quite simple to use : define what is a particle -it is a standard Javascript class – what are its properties, how does it update, draw, and spawn – and then you’ll have access to some handy functions to spawn / autoSpawn / emit particles, and also to test and monitor your engine.

JSparkle is fast, since the update phase does take very little time, and there’s nothing we can do to get the draw phase to run faster on an html5 canvas. It does not create garbage, since it uses a fixed loop buffer that allocates all particle on engine creation. Another few tricks here and there made the update time fell below 5% of the draw time on my computer.

I won’t go into a full review here of the engine and its features -it was quite an effort allready to have it work fast, commented, with a few (hopefully) clear examples… dig into the code (maybe only to read the methods comments) if you wish to know more.

You’ll find some help if you want to create your own engine in the readme.txt, but maybe the fastest way to understand is to look at an example -bubbles being the most simple-. Feel free to play with the engine, and tell me what you think.

I’d be happy to include your examples, i’m sure some of you have cool graphical ideas that would just rock with JSparkle.

I post here a few screenshots and links to the demo. Obviously, the screenshots are … well… quite still :-) so watch the demos to know hat it’s like :-) .

I explained a few times ago a quite simple way of recycling the objects created with true Javscript classes. (here).
Still there are other classes scheme, and impact -and probably other framework as well-, uses a variant of John Resig’s inheritance scheme (here).
Thoses classes rely on an init() member, that will be in charge of … -you guessed- initializing the object.
I’ll explain here this scheme, and then apply the Pooling strategy to those objects.

Extend must be provided with an object, which will be used to add properties and methods to the original Class.
All the properties and methods will be set on the protoype of the new Class (which is, in fact, a function as you know).
Then, when you create an object using new (), it will be the constructor’s responsability to copy the properties of the prototype into the new object. This copy is required because otherwise, if we take the Entity example, all entities would share the same pos / velocity / … which would probably lead to a boring game.
It is important to notice that all objects do not get copied : look at copy() (Impact.js, line 125) and you’ll see that HTMLElement or ig.Class properties won’t be copied. So they are shared amongst all instances. That is why you cannot set the animations in the extend object : each Entity needs its own animation.
But how to create those per-instance objects ? You do not have any control other the constructor function (handled by the class system), and obviously the object provided to extend the Class doesn’t know anything about the ‘this’ of the objects you’ll later instanciate…
That’s when the init() comes into play : it is called at the end of the constructor, and allows you to perform an initialization on the new instance, for all properties that needs their own instance of an ig.Class ( ex : animation), or a specific new value (x,y).

How could we recycle such objects ?

Since -to state things in a simple way-, it is now init() which initialising just like the constructor function does it for true js classes. So, to pool those classes, we just have to call init instead of the constructor to have the object as clean as new when we retrieve it from the pool.

The constraints we had on the constructor function for true js classes to work with pooling now apply on the init() function :
– init should accept any number of arguments (including none).
– at the end of an init EVERY properties should be set either to its default value OR to a value provided in the arguments of init.
So if you plan on using pooling with a Class, you must do a quick review of all properties you are using in your code, an reset or set them to the provided values in the init().

Now you are sure that any call to init will set your object as shining as new.
But.
But…
Wait !

The goal of all this is to avoid garbage creation, and the init() above will create objects on each call : So any time you can, try to re-use the property objects of the previous life of your object as well :

Rq : there are too many cases for me to explain here, but remember that when allocating an object for the pool, init will be called with no arguments. Then later, it will be called with your arguments (and *maybe* this second call is also performed with no arguments), and then again and again init will be called on each reuse. So think well about the best way to allocate the properties that uses objects. Do most work while initializing the pool if possible, and try to reset the properties in a fast and clean way.

Rq : you might use pooled object in the properties of your pooled object. It might be pooled ig.Classes or pooled true js classes. Just watch out for their disposal.

Another thing to keep in mind when using a Framework : the Framework might change some properties for you, properties that you should reset in the init.
Expl : For the Entity class, calling kill() will make this._killed to true, and make the object collides with nothing. So you have to unkill the object and restore its default collision settings…
OR … inject the framework to have it doing this for you, which i explain later.

1. Ensure the init performs a full initialisation of *all*
your object’s property, even when called with no arguments.
2. pool the class :

MonkeyEntity.setupInitPool(100);

3. Instead of the new operator, use pnew :

MonkeyEntity.pnew(...)

4. don’t forget to pdispose() instances that you won’t use any more. :

aMonkeyInstance.pdispose()

!!! Do not keep any pointer to a disposed entity. !!!

Helper for Entity classes.

Impact can handle the creation and disposal for you : if you use the standard function spawnEntity and entity.kill(), you might just as well have them handle the pooling. And while we are here, we can also have spawnEntity to restore some default values for you : _killed and the collisions settings.
I wrote a small function that injects the pooling for the Entities, so to have pooled entities, just write (in main.js for instance, where you must ‘requires’ your entities and also gaPooling.js ) :

And that’s all !
Take care of setting YOUR properties in the inits, use only the standard spawnEntity and kill functions with them (not ‘new’), and your monkeys and gorillas will swim in your pool.

Are you sure this can be usefull ?

Well, for, say, the hero entity -used only once-, i guess not. For monsters, it will depend on their number and spawning rate. For bullets, it should pretty much always useful.

You can see in my other article on Pooling some performance counter : they measure in fact a mix of the creation time and garbage collection time.
Since Javascript does not allow to know the memory use or when it performs a garbage collection, it is difficult to be accurate.
But i had this other idea : what about looking at the memory usage (in Chrome / Timeline), and measure the Garbage Collection rate by hand ? After all we know a G.C. occured when memory usage suddenly drops.
So i made a quick demo throwing quite a lot of bullets (100/s) and measured ‘by hand’ the number of G.C. performed.
As you can see, there are 0.26 GC/second with no Pooling, and 0.04 GC/second with pooling, so we have a X6 improvement. !!
We can see also that the pooled memory usage stays 2/3 MB or so below the non-pooled usage.

Memory usage when not pooling / pooling.

Let me know if you happen to use all this in your game (and are happy with it !).

So now let us watch how to handle Javascript arrays with performances in mind.

The array object is indeed very powerful, but you need to handle it with care since some quite innocent feature can be have a high time and/or garbage creation cost.

I’ll show here a few simple techniques that avoids those costs.
The performance benefits can be very high (more than 10X) for some features, so all this is worth a look.

1. Stating the obvious : [] is better than {}

Any time you can, avoid using an {} object to store data/perform computations/…
It is quite likely that you can use an integer instead of string to identify your data.
You might have to use another integer ->string array to do so, but it’s worth the performance gains.

2. [ integer ] is better then [ something else ]

In the same manner, prefer to use arrays of integers : arrays where *all* ‘slots’ of the array are filled with integers. In such a situation, most javascript engine will recognize that they are dealing with an array of integer and perform much faster.

3. Do not loop backward within an array.

You might know this way to iterate through an array :

var i = myArray.length;
while ( i-- ) {
... process myArray[i] ...
}

Which makes you avoid an extra test (compared to the standard for loop).
But you know what ? this will be much slower than using the right order.
Because all CPU caches in the world expect the processing to be ‘straight’, you will have cache misses again and again, and a 2X slow down is what you’ll get when you are lucky.

Depending on array size, and value distribution ( == ? will we find a few or a lot of matches) ?, this one might be way faster in fact.

Surprising.

4. Do not change again and again the array’s size

One important thing to notice, that is hidden by the simplicity of push(), pop(), among others, is that any time you change the size of an array it might lead to memory allocation and/or memory fragmentation and/or memory copy.
Exemple :

Just on this very simple example : 1 push, 1 pop, we are doing much more memory activity than we should : 3 memory allocation, 3 memory dis-allocation, 8 values copy (!). You have to imagine the case where you are using array of arrays, altogether with a lot of smaller objects, when such issue will become very important.

==> Push and pop are not constant time operations, but are taking a time proportional to the array’s length ( O(n) ), and memory fragmentation.

( Maybe the term ‘list’ used in other languages, is less misleading on that regard. )

Rq : Changing the length of the array directly :

myArray.length = 12 ;

might have exactly the same performance impact.

==>> Operate on fixed sized arrays whenever possible.

==>> Using over-sized array is way better than changing often the size.

Those two operation required 1 read, 1 write, 2 add.
No memory allocation, no copy : even if you add boundary checks for the pop operation, performances just can’t compare to the not-so-complex scenario exposed above.

5. Remarks on performance measures

If you happen to test performances for various cases, take great care.
Some remarks about jsperf specifically :
– In javascript, no-one knows when a garbage collector will happen, so it might even happen ‘later’, when it is no longer the test that created garbage that is running. Yet, with the high number of loops performed this effect seems not too important.- But worse : no memory is allocated before the test starts, so if we test with just one array, the memory management task is much much simpler than in real-life applications, and proves nothing : let us see an example with push/pop :

No disallocation / re-allocation / copy will never happen with a single array test, and all operations are simpler : far too simple.
I noticed that when testing pooling objects within an array with only one type of object : even IE was faster at handling memory than Chrome (!), and pooling was useless on any browser. Then i just used 3 arrays of 3 differently sized object, which is a not so complex situation. The performances of IE went down in the deep sea, and all browsers had a hard time to get their memory straight : by avoiding memory allocation/fragmentation, pooling showed impressive improvements. But the single-object test case was just too simple.
The real-life case are way harder on the garbage collector, as you can see in paragraph 4.

Conclusion : When it comes to memory issues, expect the real performance improvements to be in fact higher than the jsperf result.

6. pre-allocate your arrays whenever you can.

In case you want to fill an array with some values, allocate the needed memory at once by using the Array constructor :

was not a good idea for performance. My guess is that an array filled by both undefined
(all the n-1 first items) and integer cannot be treated internally as an integer array.

On the other hand, when using the Array constructor (new Array(length)), Firefox and Chrome at least seems to be able to optimize internally the array without problems, so keep this in mind whenever you allready know the size your array will have.

6. write your own, push, pop, unshift, splice (among others).

All those nice features are to be avoided if you need performance : because they are functions : you pay the price of a call, so if you can inline, do it.
And also because often you know something about your array the function doesn’t (expl : all items are >0 integers).
Splice is especially to be avoided, since it returns an array of removed items : slower, useless, and creating garbage.
So replace those functions by your own code, and even inline the smallest one : depending on functions, browsers and devices, the performance gain can be from 2X to 10X.

Be carefull about what are doing the arrays or array-friendly functions you use, and if you happen to use one very frequently in critical sections of your code, ask yourself if you cannot beat the javascript engine.
In quite some not-so-special cases you can.

Rq about shift/unshift : beware, those are always O(n) operations (meaning : each operation will take a time proportionnal to the number of the array length). Unless you really need to, you shouldn’t use them. Rather build your own rotating array if you need such feature.

7. Could i never de-allocate my arrays ? Yes, you can !

A nice way to avoid allocation/disallocation issues is to handle a separate index,
and to handle its pseudo-length separately. Let us call this the ‘sLength’ (stackLength)
of the array.
The code could look like :

So here, if you choose well the initial size, you have a stack with a
null memory cost for its whole life. If by any bad chance you lack space,
no special code is needed : the array will increase (with a memory cost), then
will stay in its new size. You might want to check at the end of one game the
highest stack length to avoid any such re-allocation during the game.

Rq for shift/unshift users : apply the same principle, with two indexes, to
avoid copy/reallocation. One index on the left, one on the right, both starting
at the middle of the array. Then you’ll be again in O(1) time. Better.
Don’t forget to re-center the indexes when they are ==.

If think you’ll easily figure out how to write min/max/indexOf/… such arrays, just use
the stackLength instead of the array length in the loops.

Rq about sLength.
You cannot add sLength as a property of your array (myArray.sLength = 3; )
Because by doing so you’ll transform your Array ([]) into an Object ({}), since you’d do the same as writing myArray[‘sLength’]=3. Expect the performances to drop dramatically if
you do so.

8. Some last words about Typed Array.

In javascript, one thing that makes array slower is the fact that they are, as everything in javascript, untyped.
That’s why html5 invented the typed arrays, which are super fast since they are optimized for a given type of integer. I was very excited about that, but when benchmarking or watching other’s benchmark, i quickly saw that the performance gain was null : Firefox and Chrome at least allready recognize the arrays that are integer array, so no interest in the extra coding for comon cases.

Another interest might be the ‘clamped’ array, that avoid you to test everything you write. Again a special case, but the gain might be interesting.

Last example : since you can set different views on the same buffer, you can test for some properties using one view, and do some other computation with another view.

Example : imagine you want to make a ‘tint’ effect on your canvas : if a point has a R,G,B above a given value, set the color to be brighter. Imagine also most pixels are black (0,0,0,0), so you can be much faster by testing that first : create a 32 bits view on the image to detect the black pixels at once.