Game Development Reference
In-Depth Information
way, the browser knows precisely and instantly, where in memory element nums[3]
is found which is at memory address nums + 3 . This can be done because typed
arrays are stored in a continuous chunk of memory, much like it does in array struc-
tures in C and C++ (which, by the way, is the language used to implement most, if
not all JavaScript engines).
The major use case for typed arrays is, as hinted earlier, WebGL (which we'll cover
in Chapter 6 , Adding Features to Your Game ). In WebGL, where we can perform 3D
rendering right from JavaScript, we may need to process integer buffers, over a
million elements long. These buffers can be used to represent a 3D model that we
wish to draw to the screen. Now, imagine how long it would take for the browser to
iterate through one such array. For each and every element, it would have to follow a
memory location, check the value at that location, make sure the value is a number,
attempt to convert the value into a number, and then finally use that value. Sounds
like a lot of work? Well, that's because it is. With typed arrays, it can just run through
that array as fast as it can, knowing that each element is indeed a number, and
knowing exactly how much memory each element takes, so that jumping to the next
memory address is a consistent and predictable process.
Typed arrays are also used in the 2D canvas context. As we'll see in the canvas
API section later in the chapter, there is a way that we can get the pixel data from
whatever is drawn into a canvas. All that this pixel data is, is a long array of 8bits
clamped unsigned integers . What that means is that each element in this array
can only be an integer value between 0 and 255, which is precisely what the ac-
ceptable values are for a pixel.
How to use it
Using typed arrays is really simple. It may be easier to understand how they work if
you have at least some experience with C or C++. The easiest way to create a typed
array is to declare our array variable, and assign it an instance of a particular typed
array type.
var typedArr = new Int32Array(10);
In the example, we have created an instance of an integer array, where each ele-
ment can be either positive or negative ( signed ). Each element will be stored as a
Search WWH ::




Custom Search