Skip to content

Commit 95ffb09

Browse files
committed
Add section about Enumerable#lazy
1 parent e7b5735 commit 95ffb09

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

README.adoc

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4915,6 +4915,25 @@ Predicate methods without arguments can't replace `count` expressions when colle
49154915
----
49164916
--
49174917

4918+
=== Leverage `#lazy` to Optimize Memory Usage [[leverage-lazy-to-optimize-memory-usage]]
4919+
4920+
Using `Enumerable#lazy` in combination with methods like `Enumerable#first` or `Enumerable#take` can be very efficient, especially for operations on large collections, datasets and infinite sequences seamlessly.
4921+
4922+
Enumerator::Lazy can be constructed from any Enumerable with the `Enumerable#lazy` method without evaluating them immediately, and evaluating values on as-needed basis.
4923+
4924+
The real enumeration is performed when any non-redefined Enumerable method is called.
4925+
4926+
[source,ruby]
4927+
----
4928+
# bad - instantiates the entire collection into memory first
4929+
(0..).uniq { |x| x + 2 }.first(10)
4930+
(0..10000000).select { |x| x % 1000 }.first(5)
4931+
4932+
# good - evaluates elements on an as-needed basis
4933+
(0..).lazy.uniq { |x| x + 2 }.first(10)
4934+
(0..10000000).lazy.select { |x| x % 1000 }.first(5)
4935+
----
4936+
49184937
== Numbers
49194938

49204939
=== Underscores in Numerics [[underscores-in-numerics]]

0 commit comments

Comments
 (0)