我對scala中的理解效率有疑問。scala中的理解性能
這下面的代碼需要大約45秒時的燙髮是大約550元素
perm = some list
for{
perm <- perms.withFilter(_.size > 0)
wordList = somefunction(perm) //expensive operation, wordlist is a list of strings
sentenceList = somefunction1(perm) //very expensive operation, sentenceList is a list of list of strings
word <- wordList
sentence <- sentenceList
} yield { word::sentence}
當我改變下面的代碼到下面的列表來運行,它在3秒跑用相同的燙髮列表
perm = some list
for{
perm <- perms.withFilter(_.size > 0)
word <- somefunction(perm) //expensive operation
sentence <- somefunction1(perm) //very expensive operation
} yield { word::sentence}
性能的差異是否與Scala中的懶惰評估有關?
感謝您的回答。我明白你的意思。我有一個跟進關於脫糖過程的問題。爲什麼第一條語句寫成'perms.withFilter(_。size> 0).flatMap {}'而不是'perms.withFilter(_。size> 0).foreach {}'? – Piyush 2014-11-03 18:10:34
'foreach'返回'Unit',所以你的結果將會丟失。 – drexin 2014-11-03 21:26:54
啊,我明白了。那麼對於{x < - x1,y <-y1,z <-z1} yield(x ::: y ::: z)的以下for-comprehensions轉換爲x1.flatmap {x => y1。 flatmap {y => z1.map {z => x :: y :: z}}}'? – Piyush 2014-11-03 21:54:21