klo
Concat/appending lists
Got a question about when to concat vs. prepending items to list then reversing to achieve appending.
So i know lists boil down to [1 | [2 | []]]. I also know that i can append to a list using something such as
iex(1)> list = [1, 2, 3]
[1, 2, 3]
iex(2)> list ++ [4]
[1, 2, 3, 4]
and I can prepend to a list such as
iex(3)> [4 | list]
[4, 1, 2, 3]
But to achieve what I did before on the line above, i would have to reverse the list, prepend, then reverse again. What if i tried to append a list of items? why would the fastest way be to use something such as Enum.concat or using the ++ to stitch together the two lists and not doing a recursive call that will do just prepend the bits and flip the entire list?
Most Liked
sorentwo
Or you can look at the fast-elixir benchmark which breaks down the various techniques by list size.
kip
Enum.concat/2 for two lists is implemented as:
@spec concat(t, t) :: t
def concat(left, right) when is_list(left) and is_list(right) do
left ++ right
end
![]()
gregvaughn
Down in erlang, reversing a list executes a heavily optimized native BIF (built-in-function) because it’s a frequently used feature, so it’s probably not as expensive as you think. That being said, unless your lists are long or you’re in a performance critical part of code, don’t worry too much. Do what’s most expressive.
But if you do need to optimize, be sure to benchmark. For some length of list and algorithm append may be faster, but if the length of the list changes, then prepend-then-reverse may be faster.
I find many times the ordering does not have bearing on the correctness of the code. In those cases I prepend out of habit.
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









