From 95ffb09fb1afe8a53015b284eba9231bb6df464a Mon Sep 17 00:00:00 2001 From: Yauheni Dakuka Date: Fri, 15 Dec 2023 16:58:39 +0400 Subject: [PATCH] Add section about Enumerable#lazy --- README.adoc | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.adoc b/README.adoc index cb5b0333..3f1eb5bc 100644 --- a/README.adoc +++ b/README.adoc @@ -4915,6 +4915,25 @@ Predicate methods without arguments can't replace `count` expressions when colle ---- -- +=== Leverage `#lazy` to Optimize Memory Usage [[leverage-lazy-to-optimize-memory-usage]] + +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. + +Enumerator::Lazy can be constructed from any Enumerable with the `Enumerable#lazy` method without evaluating them immediately, and evaluating values on as-needed basis. + +The real enumeration is performed when any non-redefined Enumerable method is called. + +[source,ruby] +---- +# bad - instantiates the entire collection into memory first +(0..).uniq { |x| x + 2 }.first(10) +(0..10000000).select { |x| x % 1000 }.first(5) + +# good - evaluates elements on an as-needed basis +(0..).lazy.uniq { |x| x + 2 }.first(10) +(0..10000000).lazy.select { |x| x % 1000 }.first(5) +---- + == Numbers === Underscores in Numerics [[underscores-in-numerics]]