How could I speed up the code

This is sort of true. Where Stream tends to win is on memory, if you can avoid loading the entire dataset into memory. It can also win on speed if you have several composed calls data |> map(a) |> map(b) |> map(c) and those are Stream.map calls then it’ll do it in a single pass instead of 3. BUT for a single pass, eager iteration is faster, because streams impose some overhead to allow them to gain the other benefits. Thus if you turn the 3 map operations into data |> map(& &1 a |> b |> c) eager is probably faster.

@anuarsaeed The logic is slow here for a few reasons. The main reason it’s slow is this: Computing permutations is intrinsically slow. Some algorithms, like counting how many items are in a list, get a little bit slower each time you make the list longer. Some algorithms though, like computing permutations, get a LOT slower as you add items. There is a “mathy” or formal way of looking at this kind of “slowness relative to inputs” called Big O notation, and the big O for permutations is pretty bad, the time it takes grows pretty fast.

The second reason it’s slow though does have to do with how you wrote it. I’d check out Most elegant way to generate all permutations? for an alternative implementation.

4 Likes