Created
March 2, 2013 01:53
-
-
Save wycats/5069291 to your computer and use it in GitHub Desktop.
Lazy enumerations reduce allocations
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
class LoggedChar < Struct.new(:char) | |
def downcase | |
puts "downcasing #{char}" | |
char.downcase | |
end | |
def capitalized? | |
puts "capitalized? #{char}" | |
char =~ /[A-Z]/ | |
end | |
end | |
array = %w(a B c D e F g).map { |char| LoggedChar.new(char) } | |
puts "## NORMAL ITERATION ##" | |
puts | |
p array.select(&:capitalized?).map(&:downcase) | |
puts | |
puts | |
puts "## LAZY ITERATION ##" | |
puts | |
p array.lazy.select(&:capitalized?).map(&:downcase).to_a | |
# OUTPUT | |
# ------ | |
# | |
# ## NORMAL ITERATION ## | |
# | |
# capitalized? a | |
# capitalized? B | |
# capitalized? c | |
# capitalized? D | |
# capitalized? e | |
# capitalized? F | |
# capitalized? g | |
# downcasing B | |
# downcasing D | |
# downcasing F | |
# ["b", "d", "f"] | |
# | |
# | |
# ## LAZY ITERATION ## | |
# | |
# capitalized? a | |
# capitalized? B | |
# downcasing B | |
# capitalized? c | |
# capitalized? D | |
# downcasing D | |
# capitalized? e | |
# capitalized? F | |
# downcasing F | |
# capitalized? g | |
# ["b", "d", "f"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment