~kb/sparse

5370ad67af788fab4e2f41d6de1ccfa5e0ace390 — Kim Burgess 3 years ago ab6dc9e
Improve perf of element insertion
1 files changed, 9 insertions(+), 8 deletions(-)

M src/sparse/vector.cr
M src/sparse/vector.cr => src/sparse/vector.cr +9 -8
@@ 62,19 62,20 @@ module Sparse
    #
    # If duplicate values exists for the same index, the result of callig *dup*
    # with the previes and new values will be stored.
    #
    # Passed elements do _not_ need to be sorted.
    def build(indicies : Indexable(UInt64), values : Indexable(T), dup : T, T -> T) : self
      raise "cannot build into a populated Vector" unless nvals.zero?
      seen = Set(UInt64).new
      indicies.zip values do |idx, val|
        next if idx >= size
        if idx.in? seen
        if seen.add? idx
          set_element idx, val
        else
          old = unsafe_fetch(idx).not_nil!
          val = dup.call old, val
          set_element idx, val if old != val
        else
          set_element idx, val
        end
        seen << idx
      end
    end



@@ 83,10 84,10 @@ module Sparse
      check_index_out_of_bounds index
      pos = @idx.bsearch_index &.>=(index)
      if pos.nil?
        @idx << index.to_u64
        @val << value
      elsif @idx[pos] == index
        @val[pos] = value
        @idx.push index.to_u64
        @val.push value
      elsif @idx.unsafe_fetch(pos) == index
        @val.to_unsafe[pos] = value
      else
        @idx.insert pos, index.to_u64
        @val.insert pos, value