Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason <em>that</em> particular code is slow is because it's working on primitives but it's using generic operations, so the primitives have to be boxed. (This could be improved if <code>List</code> and its ancestors were specialized.) This will probably slow things down by a factor of 5 or so.</p> <p>Also, algorithmically, those operations are somewhat expensive, because you make a whole list, and then make a whole new list throwing a few components of the intermediate list away. If you did it in one swoop, then you'd be better off. You could do something like:</p> <pre><code>list collect (case e if (e*2&gt;10) =&gt; e*2) </code></pre> <p>but what if the calculation <code>e*2</code> is really expensive? Then you could</p> <pre><code>(List[Int]() /: list)((ls,e) =&gt; { val x = e*2; if (x&gt;10) x :: ls else ls } </code></pre> <p>except that this would appear backwards. (You could reverse it if need be, but that requires creating a new list, which again isn't ideal algorithmically.)</p> <p>Of course, you have the same sort of algorithmic problems in Java if you're using a singly linked list--your new list will end up backwards, or you have to create it twice, first in reverse and then forwards, or you have to build it with (non-tail) recursion (which is easy in Scala, but inadvisable for this sort of thing in either language since you'll exhaust the stack), or you have to create a mutable list and then pretend afterwards that it's not mutable. (Which, incidentally, you can do in Scala also--see <code>mutable.LinkedList</code>.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload