def make_parts(iterator, internal_sorter)
        slice = START_SLICE_SIZE

        parts = []
        part  = []

        loop do
          begin
            # Enumerator does not have slice method
            slice.times { part << iterator.next }
          rescue StopIteration
            break
          end

          # Carefully memory_limit is variable
          if memory_usage > memory_limit
            # Sort current part with origin key_function
            internal_sorter.sort(part)
            # Tempfile for current part
            # will be destroyed on #destroy_temp_folder
            file = Tempfile.new("part", @dir)
            serializer.dump(part, file)
            # Peek is at the end of file
            file.seek(0)
            parts << serializer.load(file)

            # Some memory will be released but not immediately
            # need some new memory for start
            part.clear
            add_memory!
          else
            slice = [slice*2, MAX_SLICE_SIZE].min
          end
        end

        # Last part which is not in the file
        if part.any?
          internal_sorter.sort(part)
          parts << part.each
        end

        parts
      end
def make_parts(iterator, internal_sorter)
        slice = START_SLICE_SIZE

        parts = []
        part  = []

        loop do
          begin
            # Enumerator does not have slice method
            slice.times { part << iterator.next }
          rescue StopIteration
            break
          end

          # Carefully memory_limit is variable
          if memory_usage > memory_limit
            # Sort current part with origin key_function
            internal_sorter.sort(part)
            # Tempfile for current part
            # will be destroyed on #destroy_temp_folder
            file = Tempfile.new("part", @dir)
            serializer.dump(part, file)
            # Peek is at the end of file
            file.seek(0)
            parts << serializer.load(file)

            # Some memory will be released but not immediately
            # need some new memory for start
            part.clear
            add_memory!
          else
            slice = [slice*2, MAX_SLICE_SIZE].min
          end
        end

        # Last part which is not in the file
        if part.any?
          internal_sorter.sort(part)
          parts << part.each
        end

        parts
      end
New part is created when current part exceeds memory limit (is variable)
 Every new part have more memory because of ruby GC