I think you overestimate the CPU load for option 1. Option one
"Iterate through the array, setting the values as you go." is the most
logical and best choice.
Check out the fiddle here: http://jsfiddle.net/qmUFh/10/
On my machine these are the timing in chrome:
for 0.000003814697265625 MB 1 items it took 0.08099999831756577 ms
for 0.00003814697265625 MB 10 items it took 0.019999999494757503 ms
for 0.0003814697265625 MB 100 items it took 0.0040000013541430235 ms
for 0.003814697265625 MB 1000 items it took 0.016999998479150236 ms
for 0.03814697265625 MB 10000 items it took 0.15299999358830974 ms
for 0.3814697265625 MB 100000 items it took 0.8980000056908466 ms
for 3.814697265625 MB 1000000 items it took 6.201999996847007 ms
for 38.14697265625 MB 10000000 items it took 58.27299999509705 ms
for 381.4697265625 MB 100000000 items it took 591.3989999971818 ms
It takes half a second to clear almost 400mb. 400mb is more then any
one can safely use for a web game and it takes only half a second to
One cant even "feel" smaller arrays being cleared.
Option 1 is the best method and I dont think any thing will be gained
by implementing "long" TypedArray#set() natively.
You will be running into same memory slowdown in C as you do in JS.
On Wed, Nov 21, 2012 at 6:50 AM, Jussi Kalliokoski
> Hi everyone,
> When you create a typed array, its values are automatically initialized to
> zero. However, there seems to be no good way to do this after the array is
> created and modified.
> Options are:
> * Iterate through the array, setting the values as you go. Unnecessarily
> * use .set() with a new Typed Array instance, e.g.
> var arr = new Float32Array(20)
> // do something with the array
> arr.set(new Float32Array(arr.length))
> but this comes with a memory allocation overhead and possibly GC as well.
> * Keep a reference to an array full of zeroes, and use .set() with this.
> This doesn't suffer from the earlier problems, but significantly reduces the
> code readability and might require a lot of memory, especially if you're
> reusing the array for multiple targets for best performance gain.
> I suggest adding an overload to TypedArray#set(), taking a number to which
> all of the array is set to.