开发者

rails - how much faster are number comparisons vs text comparisons

I have a pretty expensive method in my model that compares text items of arrays for many many items.

It runs really slow. If I use a relational database table and compare the ID's only, will my method run a lot faster?

/EDIT

I'm attempting to benchmark the below:

 @matches = @location_开发者_运维知识库matches.sort do |l1, l2|
      l1.compute_score(current_user) <=> l2.compute_score(current_user)
    end

    @matches.reverse!


To be short, I guess number comparison will be faster because comparing string is about comparing character after character (advice: in Ruby use symbols when you can, their comparison is much faster).

Whatever, you'll find there, everything you need to benchmark and get your detailled results.

A code sample:

require 'benchmark'

n = 50000
Benchmark.bm do |x|
  x.report("for:")   { for i in 1..n; a = "1"; end }
  x.report("times:") { n.times do   ; a = "1"; end }
  x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
end

The result:

                user     system      total        real
   for:     1.050000   0.000000   1.050000 (  0.503462)
   times:   1.533333   0.016667   1.550000 (  0.735473)
   upto:    1.500000   0.016667   1.516667 (  0.711239)


Your first task is to replace that sort with a sort_by, you can also skip the reverse! by sorting things in the desired order in the first place:

@matches = @location_matches.sort_by { |loc| -loc.compute_score(current_user) }

The sort method will have to do many comparisons while sorting and each comparison requires two compute_score calls, the sort_by method does a Schwartzian Transform internally so your expensive compute_score will only be called once per entry. The negation inside the block is just an easy way to reverse the sort order (I'm assuming that your scores are numeric).

Fix up the obvious performance problem and then move on to benchmarking various solutions (but be sure to benchmark sort versus sort_by just to be sure that "obvious" matches reality).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜