Browse Source

[ruby/agoo] Improve sorting (#8474)

Using `sort_by` is faster for more complex objects.
It's also what is used by the other Rub frameworks.

```ruby
require 'benchmark/ips'

ms = []
ms << { message: 'fortune: No such file or directory' }
ms << { message: 'A computer scientist is someone who fixes things that aren''t broken.' }
ms << { message: 'After enough decimal places, nobody gives a damn.' }
ms << { message: 'A bad random number generator: 1, 1, 1, 1, 1, 4.33e+67, 1, 1, 1' }
ms << { message: 'A computer program does what you tell it to do, not what you want it to do.' }
ms << { message: 'Emacs is a nice operating system, but I prefer UNIX. — Tom Christaensen' }
ms << { message: 'Any program that runs right is obsolete.' }
ms << { message: 'A list is only as strong as its weakest link. — Donald Knuth' }
ms << { message: 'Feature: A bug with seniority.' }
ms << { message: 'Computers make very fast, very accurate mistakes.' }
ms << { message: '<script>alert("This should not be displayed in a browser alert box.");</script>' }
ms << { message: 'フレームワークのベンチマーク' }

Benchmark.ips do |b|
  b.report("Sort")    { ms.sort{|x,y| x[:message] <=> y[:message]} }
  b.report("Sort by") { ms.sort_by { |x| x[:message] } }
end
```

```bash
Calculating -------------------------------------
                Sort    226.307k (± 2.9%) i/s -      1.148M in   5.075409s
             Sort by    453.959k (± 3.2%) i/s -      2.278M in   5.022372s
```
Petrik de Heus 1 year ago
parent
commit
88bb2996a0
1 changed files with 1 additions and 1 deletions
  1. 1 1
      frameworks/Ruby/agoo/app.rb

+ 1 - 1
frameworks/Ruby/agoo/app.rb

@@ -114,7 +114,7 @@ class FortunesHandler < BaseHandler
 
     f_2 = f_1.map(&:to_h).
             append({ 'id' => '0', 'message' => 'Additional fortune added at request time.' }).
-              sort { |x,y| x['message'] <=> y['message'] }.
+              sort_by { |item| item['message'] }.
                 map { |f| "<tr><td>#{ f['id'] }</td><td>#{ Rack::Utils.escape_html(f['message']) }</td></tr>" }.
                   join