21 ms·
>Now it's going to have to construct each string, then create a new string with all three. More creation & copying means things get slower. There's nothing abo
by coldtea 10y ago
>Now it's going to have to construct each string, then create a new string with all three. More creation & copying means things get slower.
There's nothing about the ++ syntax that makes it necessarily so. The compiler/interpreter could understand that we're getting a concatenated string and automatically only create one.
Which is the case in several languages.
- filmor 10y agoWhat is different in Erlang is that strings are a bit messed up in that they are linked lists of numbers. What you are suggesting (constructing the actual string in-place) works fine in Erlang, too, but has a bit of a funky syntax: welcome_user(Username) -> << <<"Welcome ">>/binary, Username/binary, <<"!">>/binary >>. However, the main advantage of using io_lists instead is that `["Welcome", Username, "!"]` has constant complexity with regard to the length of `Username`.
- diamondlovesyou 10y agoNote to anyone not already familiar: in Elixir, character strings are all binaries from the start. Just to avoid the notion that Elixir follows the mistake of strings-are-linked-lists from Erlang.
- IanCal 10y agoThis could be true in some restricted cases, but can't be in general. If the username came from the database, it's going to be stored in memory before this function is called, and so concatenating must require building a new string.
- coldtea 10y agoIt can require building a new string. But what is argued is that it wont require building several new strings incrementally for each concatenation. E.g. no: A + B + C + D -> AB + C + D -> ABC + D -> ABCD And for immutable strings, it might not even require to build a new string at all, even if the string is in memory: it can just use a string data structure pointing to the various parts. (