Skip to content

Instantly share code, notes, and snippets.

@tanishiking
Last active December 24, 2015 17:06
Show Gist options
  • Save tanishiking/fb627131251a5e2aec5a to your computer and use it in GitHub Desktop.
Save tanishiking/fb627131251a5e2aec5a to your computer and use it in GitHub Desktop.
scala> (1 to 10000000).filter(_ % 2 == 0).take(5)
// Range(1, 2, ...., 10000000) というコレクションを展開した上で
// 全てに対して filter などの処理がが行われるためメモリに大きな負担を与え
// 最終的に必要なのは前方5つだけなのに全体をなめるので処理にかなり時間がかかる.
scala> (1 to 10000000).view.filter(_ % 2 == 0).take(5).force
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(5, 10, 15, 20, 25)
// filter や take は遅延評価される
// force メソッドで正格なコレクションに戻すことができる.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment