Little performance fix.

87 views
Skip to first unread message

Dmitry Gautsel

unread,
Apr 24, 2016, 4:41:37 PM4/24/16
to Ruby on Rails: Core
Hi all.

I have read activesupport module and found little issue.

class Array

  # current behaviour
  def split(value = nil)
    if block_given?
      inject([[]]) do |results, element|
        if yield(element)
          results << []
        else
          results.last << element
        end

        results
      end
    else
      results, arr = [[]], self.dup
      until arr.empty?
        if (idx = arr.index(value))
          results.last.concat(arr.shift(idx))
          arr.shift
          results << []
        else
          results.last.concat(arr.shift(arr.size))
        end
      end
      results
    end
  end

  # proposed behaviour
  def split2(value = nil)
    if block_given?
      inject([[]]) do |results, element|
        if yield(element)
          results << []
        else
          results.last << element
        end

        results
      end
    else
      (idx = index(value)) ? [first(idx), last(size-idx-1)] : [self]
    end
  end
end 

arr = (1..12).to_a

Benchmark.ips do |x|
  x.report('before') { arr.split(3) }
  x.report('after') { arr.split2(3) }
end

Calculating -------------------------------------
              before    42.191k i/100ms
               after    92.326k i/100ms
-------------------------------------------------
              before    660.494k (± 1.6%) i/s -      3.333M
               after      2.521M (± 1.6%) i/s -     12.649M

If you think it's OK, I will fix it.

Regards, Dmitry.

Jeremy Daer

unread,
Apr 24, 2016, 4:56:46 PM4/24/16
to Ruby on Rails: Core
Please do! Thank you Dmitry.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-co...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages