Optimal way of using the ++ operator

Hello everyone, I have heard from some colleagues that using the ++ operator is not as “bad” as I’m used to hear. However, using it correctly or in an optimal way is crucial in order to avoid poor results. What is the correct way to append a list to another, assuming I have to list that have the following lengths : list_1 = 2000, list_2 = 200_000 . Is it okay just to append the shortest list first? list_1 ++ list_2

1 Like

Hi @tovarchristian21, you can find the whole thing in the docs: The complexity of a ++ b is proportional to length(a)

1 Like

So based on my example @rodrigues, do you think it is way better to prepend every element from list_1, one by one?

Benchee would be a nice way for you to figure that out – and tell us afterwards :smile:


If you already have the lists constructed, the fastest thing to do is list_1 ++ list_2. The only possible thing that could be faster would be to, instead of constructing list_1 at all, take list_2 and prepend items one at a time from the start.


As @benwilson512 said, your best bet is not having to merge the lists at all. If you can, merge them as you construct them, element by element That way you are only doing one list merge operation while otherwise you do three: (1) construct first list, (2) construct second list, (3) merge both.

If you can avoid that three-step process, you will score a big win.