nus-cs2103-AY1718S1 / forum

Discussion Forum
5 stars 0 forks source link

Benefit of Streams as an internal iterator #99

Open AceCentury opened 6 years ago

AceCentury commented 6 years ago

Is there any real benefit to using Streams (as an internal iterator) as opposed to for loops or list iterators?

Apart from higher level of abstraction and shorter codes.

Time complexity wise isn't it still O(n)? (Excluding parallel streams)

Also, won't this be a problem as Streams requires Java 8, which would cause your program to not be backwards compatible?

Zhiyuan-Amos commented 6 years ago

What you've said is correct, except perhaps for:

Time complexity wise isn't it still O(n)? (Excluding parallel streams)

Parallel stream is still O(n) e.g. if you have 2 threads, then it's O(1/2 n) == O(n).

You can find good sources online (next time Google first and paste your findings! :P):

  1. https://blog.jooq.org/2015/12/08/3-reasons-why-you-shouldnt-replace-your-for-loops-by-stream-foreach/
  2. https://stackoverflow.com/questions/44180101/in-java-what-are-the-advantages-of-streams-over-loops

There's additional things that aren't covered here, but I'll leave it to you to find out ^^

AceCentury commented 6 years ago

Thanks for sharing your insights to this matter. I also did try some Google searching before posting, though most of them reinforced my initial guess about code readability and abstraction. So just wanted to confirm since you can't always trust what you Google.

Though I'm getting mixed things about Parallel streams, specifically how they are recommended if (number of elements * cost per element) is large and there is an availability of cores.

damithc commented 6 years ago

Apparently, using streams can even slow down the code http://blog.takipi.com/benchmark-how-java-8-lambdas-and-streams-can-make-your-code-5-times-slower/

AceCentury commented 6 years ago

Yes, I guess that is to be expected since it's a higher level of abstraction, thus the additional overheads. Though it is rather interesting how sometimes parallel streams can actually save time despite the additional overheads. (With reference to my previous post. Also, this is just me voicing my curiosity, not a factual statement)