Referencing stuff instead of hardcoding is slower.
while (counter != -1) {
counter-=1;
}
With that, going from 0 to array length is slower because you are refering to array length. Use from length-1 to -1, not 0 to array length. Both with only valid values should be.