Skip to content

Commit ae68525

Browse files
authored
[ruby/rack] Reduce random_id calls in update (#8857)
Calling `Array#sample` with a size x is faster than calling `rand` x times.
1 parent 61ea1df commit ae68525

File tree

1 file changed

+10
-19
lines changed

1 file changed

+10
-19
lines changed

frameworks/Ruby/rack/pg_db.rb

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ def prepare_statements
3737
end
3838

3939
def select_random_world
40-
@world_select.call(id: random_id)[0]
40+
select_world(random_id)
4141
end
4242

4343
def select_world(id)
44-
@world_select.call(id: id)[0]
44+
@world_select.call(id: id).first
4545
end
4646

4747
def validate_count(count)
@@ -57,40 +57,30 @@ def validate_count(count)
5757

5858
def select_promises(count)
5959
count = validate_count(count)
60-
promises = []
61-
count.times do
60+
ALL_IDS.sample(count).map do |id|
6261
@connection.synchronize do
63-
promises << @connection['SELECT id, randomNumber FROM World WHERE id = ?', random_id].async.first
62+
@connection['SELECT id, randomNumber FROM World WHERE id = ?', id].async.first
6463
end
6564
end
66-
promises
6765
end
6866

6967
def select_random_numbers(count)
7068
count = validate_count(count)
71-
results = []
72-
count.times do
73-
results << @world_random_select.call(randomvalue: random_id, id: random_id)[0]
69+
ALL_IDS.sample(count).map do |id|
70+
@world_random_select.call(randomvalue: random_id, id: id).first
7471
end
75-
results
7672
end
7773

7874
def select_worlds(count)
7975
count = validate_count(count)
80-
results = []
81-
count.times do
82-
results << @world_select.call(id: random_id)[0]
76+
ALL_IDS.sample(count).map do |id|
77+
@world_select.call(id: id).first
8378
end
84-
results
8579
end
8680

8781
def select_worlds_async(count)
8882
promises = select_promises(count)
89-
results = []
90-
promises.each do |p|
91-
results << p.to_hash
92-
end
93-
results
83+
promises.map(&:to_hash)
9484
end
9585

9686
def update_worlds(count, async = false)
@@ -111,6 +101,7 @@ def update_worlds(count, async = false)
111101
@connection[sql].update
112102
results
113103
end
104+
114105
def select_fortunes
115106
@fortune_select.call
116107
end

0 commit comments

Comments
 (0)