Skip to content

Commit 88bb299

Browse files
authored
[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 ```
1 parent 13a877f commit 88bb299

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

frameworks/Ruby/agoo/app.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def self.call(_req)
114114

115115
f_2 = f_1.map(&:to_h).
116116
append({ 'id' => '0', 'message' => 'Additional fortune added at request time.' }).
117-
sort { |x,y| x['message'] <=> y['message'] }.
117+
sort_by { |item| item['message'] }.
118118
map { |f| "<tr><td>#{ f['id'] }</td><td>#{ Rack::Utils.escape_html(f['message']) }</td></tr>" }.
119119
join
120120

0 commit comments

Comments
 (0)