presto-main/src/main/java/io/prestosql/operator/aggregation/TypedHeap.java/TypedHeap/compactIfNecessary
class TypedHeap:    private void compactIfNecessary()
    {
        // Byte size check is needed. Otherwise, if size * 3 is small, BlockBuilder can be reallocate too often.
        // Position count is needed. Otherwise, for large elements, heap will be compacted every time.
        // Size instead of retained size is needed because default allocation size can be huge for some block builders. And the first check will become useless in such case.
        if (heapBlockBuilder.getSizeInBytes() < COMPACT_THRESHOLD_BYTES || heapBlockBuilder.getPositionCount() / positionCount < COMPACT_THRESHOLD_RATIO) {
            return;
        }
        BlockBuilder newHeapBlockBuilder = type.createBlockBuilder(null, heapBlockBuilder.getPositionCount());
        for (int i = 0; i < positionCount; i++) {
            type.appendTo(heapBlockBuilder, heapIndex[i], newHeapBlockBuilder);
            heapIndex[i] = i;
        }
        heapBlockBuilder = newHeapBlockBuilder;
    }