Created
July 11, 2013 01:22
-
-
Save Erol/5971754 to your computer and use it in GitHub Desktop.
Make selecting or rejecting items from an Ohm collection faster by getting only selected fields.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
User.all.size | |
#=> 30000 | |
# BEFORE | |
Benchmark.measure { User.all.select { |user| user.firstname =~ /Erol/ } } | |
#=> 66.630000 1.070000 67.700000 ( 67.868905) | |
# AFTER | |
Benchmark.measure { User.all.select(:firstname) { |firstname| firstname =~ /Erol/ } } | |
#=> 2.080000 0.020000 2.100000 ( 2.231251) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Ohm::Collection | |
def select(*atts) | |
return Enumerator.new(self, :select, *atts) unless block_given? | |
return super if atts.empty? | |
ids = key.sort(by: '#', get: ['#'] + atts.map { |att| "#{model.key}:*->#{att}" }) | |
.select { |values| yield *values.slice(1..-1) } | |
.map { |values| values[0] } | |
fetch ids | |
end | |
def reject(*atts) | |
return Enumerator.new(self, :select, *atts) unless block_given? | |
return super if atts.empty? | |
ids = key.sort(by: '#', get: ['#'] + atts.map { |att| "#{model.key}:*->#{att}" }) | |
.reject { |values| yield *values.slice(1..-1) } | |
.map { |values| values[0] } | |
fetch ids | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment