I need to store 16 values in a class, representing a 4x4 grid of numbers. Initially I was using number but I know that’s slow. Converting to number and just doing index = 4 * y + x
is easy enough, but I was wondering if I could make it faster.
I did some testing with a buffer, and it seems to be significantly slower. I tried both Float32LE and Float32BE and there didn’t seem to be much difference. I know I could also do something like public v00: number, v01: number ... v32: number, v33: number
but that would be a pain to work with and loop through. Am I using buffers or getting and setting numbers incorrectly? Also, is this way of benchmarking at all accurate? Thanks.
Test code:
// initial setup, doesn't count for performance
// set up 16 element 1D array
let myArr: number[] = [];
for (let i = 0; i < 16; i++) {
myArr.push(i);
}
// 4 bytes per float
let myBuf = Buffer.create(16 * 4);
let format = NumberFormat.Float32LE;
// actual test
let samples = 10;
let totals = [0, 0];
let n = 100000;
// do 2 sets and 1 get n times to each
for (let s = 0; s < samples; s++) {
pause(1);
let t0 = game.runtime();
for (let i = 0; i < n; i++) {
let index = i % 16;
myArr[index] = i * 3.0;
myArr[index] = myArr[index] / 2.2;
}
pause(1);
let t1 = game.runtime();
totals[0] += t1 - t0;
}
for (let s = 0; s < samples; s++) {
pause(1);
let t0 = game.runtime();
for (let i = 0; i < n; i++) {
let index = 4 * (i % 16);
myBuf.setNumber(format, index, i * 3.0);
myBuf.setNumber(format, index, myBuf.getNumber(format, index) / 2.2);
}
pause(1);
let t1 = game.runtime();
totals[1] += t1 - t0;
}
let averages = [totals[0] / samples, totals[1] / samples];
game.splash("arr: " + averages[0] + "ms", "buf: " + averages[1] + "ms");