Speed up threshold calculation code by avoiding reallocation of arrays