presto-main/src/main/java/io/prestosql/operator/aggregation/TypedKeyValueHeap.java/TypedKeyValueHeap/compactIfNecessary
class TypedKeyValueHeap:    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 (keyBlockBuilder.getSizeInBytes() < COMPACT_THRESHOLD_BYTES || keyBlockBuilder.getPositionCount() / positionCount < COMPACT_THRESHOLD_RATIO) {
            return;
        }
        BlockBuilder newHeapKeyBlockBuilder = keyType.createBlockBuilder(null, keyBlockBuilder.getPositionCount());
        BlockBuilder newHeapValueBlockBuilder = valueType.createBlockBuilder(null, valueBlockBuilder.getPositionCount());
        for (int i = 0; i < positionCount; i++) {
            keyType.appendTo(keyBlockBuilder, heapIndex[i], newHeapKeyBlockBuilder);
            valueType.appendTo(valueBlockBuilder, heapIndex[i], newHeapValueBlockBuilder);
            heapIndex[i] = i;
        }
        keyBlockBuilder = newHeapKeyBlockBuilder;
        valueBlockBuilder = newHeapValueBlockBuilder;
    }