David suggested changes, use Vector.valuesIterator where possible instead of .toArray to reduce copying