Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3.4. SHOULD be mindful of the garbage collector — Incorrect example #36

Open
Aivean opened this issue Feb 22, 2016 · 2 comments
Open

Comments

@Aivean
Copy link

Aivean commented Feb 22, 2016

https://github.com/alexandru/scala-best-practices/blob/master/sections/3-architecture.md#34-should-be-mindful-of-the-garbage-collector

someCollection
 .filter(Set(a,b,c).contains)
 .map(_.name)
First of all, this creates a Set every single time, on each element of our collection.

This is not true. Set is created only once and then its contains function is passes as an argument to filter method. This function is then invoked per each element of someCollection.

Compare to similar code snippet:

someCollection
 .filter(Set(a,b,c).contains(_))
 .map(_.name)

In this case a wrapping function is be created around Set(a,b,c).contains, something like x:Int => Set(a,b,c).contains(x) and this function is then passed as an argument for filter. Set is created inside wrapping function, so it's creation is performed once per element of someCollection.


Also, in this item it is worth to mention eagerness of monadic operations on scala collections.
In provided example:

  .filter(bySomething)
  .map(toSomethingElse)
  .filter(again)
  .headOption

by default each step produces new collection (opposite to laziness of C#'s linq), which produces lots of garbage when chain is long.

Easy way (though no obvious) is to add .view at the beginning of the chain. This makes whole chain lazy.

@alexandru
Copy link
Owner

This is not true. Set is created only once and then its contains function is passes as an argument to filter method. This function is then invoked per each element of someCollection.

You're right. Will fix.

Easy way (though no obvious) is to add .view at the beginning of the chain. This makes whole chain lazy.

Views are considered deprecated. Iterable is better.

@Aivean
Copy link
Author

Aivean commented Feb 24, 2016

Views are considered deprecated. Iterable is better.

Sorry, can you provide a source for that statement? Quick search over internet gave nothing, as well as scaladocs for scala 2.11.6.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants