Game Development Reference
In-Depth Information
Typed arrays
Over the years, JavaScript engines have become amazingly faster. However, simply
being able to process data faster doesn't necessarily equate to being able to do more
powerful things. Take WebGL, for example. Just because the browser now has the
ability to understand OpenGL ES, it doesn't necessarily mean that it has all the tools
we developers need to take advantage of that.
The good news is that the JavaScript language has also made some progress in order
to satisfy this, and other needs that have come about. One such addition to JavaScript
in recent years is a new data type: typed arrays. In general, typed arrays offer a struc-
ture similar to the array type already in JavaScript. However, these new arrays are
much more efficient, and were designed with binary data in mind.
Why and how are typed arrays more efficient than regular arrays, you ask? Well, let's
look at a trivial example, where all we do is traverse an array of integers the old way.
Although most JavaScript engines don't particularly struggle to get this task done fairly
fast, let us not overlook all the work the engine needs to do in order to do this.
var nums = [1, 2, 3, 4, 5];
for (var i = 0, len = nums.length; i < len; i++)
{
// ...
}
Since JavaScript is not strongly typed, the array nums is not restricted to holding data
of any particular type. Furthermore, the nums array can store a different data type for
each element in it. While this can sometimes be convenient for a programmer, the
JavaScript engine needs to figure out where each element is stored, and what data
type is being stored at said location. Contrary to what you may think, those five ele-
ments in the nums array may not be stored in a contiguous piece of memory, because,
well, that's how JavaScript does it.
With typed arrays, on the other hand, each element in the array can only be an in-
teger or a float . Based on the type of array we choose, we can have a different
type of integer or float ( signed , unsigned , 8, 16, or 32 bits), but every element
in the array is always the same data type we decide to use (integer or float). This
Search WWH ::




Custom Search