I have a performance critical queue container that does a lot of random inserts/deletes. In my container class, I have a fixed size Uint32Array called updates and in my insert logic, I need to compare a value to every value in this update array.
Originally, I did it simply like this:
const u = this.updates;
for (let i = 0; i < u.length; i++) bucket_offset += bi >= u[i];
Then, just as I was putting finishing touches on the container and just screwing around, I tried unrolling said loop
const u = this.updates;
bucket_offset += (bi >= u[0]) + (bi >= u[1]) + (bi >= u[2]) + (bi >= u[3]) + (bi >= u[4]) + (bi >= u[5]) + (bi >= u[6]) + (bi >= u[7]) + (bi >= u[8]) + (bi >= u[9]) + (bi >= u[10]) + (bi >= u[11]) + (bi >= u[12]) + (bi >= u[13]) + (bi >= u[14]) + (bi >= u[15]);
And turns out this is around 10x faster on chrome, making the whole insert ~30% faster.
After that revelation, I’m looking for a way to make the VM understand that its okay to unroll that loop, after all, this.updates.length is a constant.
At the end of the day, it can stay the way it is but I’d prefer a loop since it would just look nicer. Any ideas?