OK to add properties to Typed Array?

296 views Asked by At

I've a typed array (a 4-element Uint8ClampedArray, used for colors) that I would like to add a few properties to, object-like. One, for example, will be a Uint32 view to quickly get the pixel value. Optionally an other pair would be a map/index pair for where the color is in a colormap.

It's possible, i.e. no error and works correctly, but will it cause performance problems, or some other undesired side effect?

I won't be iterating over it, just accessing via color[n], n in 0-3, so that won't be an issue, and accessing properties by their names.

I ask because Typed Arrays were added as a highly performant, device independent, interchange .. like between the cpu and the gpu, and I'd like to not screw that up.

1

There are 1 answers

0
JDB On BEST ANSWER

A simple performance test does not appear to show any kind of meaningful difference when accessing elements of the array if the array has custom properties.

See the test results here:

http://jsperf.com/uint8clampedarray-with-custom-properties

Or, run the test yourself using the following code:

Preparation Code

var i, val;

var uintc8_vanilla_array = new Uint8ClampedArray(200);
for ( i = 0; i < 200; i++ ){
  uintc8_vanilla_array[i] = "foobar";
}

var uintc8_custom_array = new Uint8ClampedArray(200);
uintc8_custom_array.foo = "bar";
for ( i = 0; i < 200; i++ ){
  uintc8_custom_array[i] = "foobar";
}

Control

for ( i = 0; i < 200; i++ ){
  val = uintc8_vanilla_array[i];
}

Custom Properties Test

for ( i = 0; i < 200; i++ ){
  val = uintc8_custom_array[i];
}

Results

enter image description here