简体   繁体   中英

Efficiency of IO lists in elixir/erlang

I have read about the efficiency of IO lists. However I am still not able to wrap my head around it.

  1. How exactly is nesting of IO list more efficient than concatenating strings.

  2. How exactly is IO list more efficient when there are a lot of repeating words.

I had used this link for reference.

Disclaimer: I will use Erlang syntax because it is how it is done in BEAM VM even in Elixir.

  1. If you have two lists LM and LN of length M and N . Then appending LM ++ LN is O(M) operation. [LM|LN] is O(1) operation. If you have two binaries BM and BN then <<BM/binary, BN/binary>> is O(M+N) operation and [BM|BN] (Yes, it is valid io_list .) is still O(1) operation.

  2. Repeating the same word W of length W regardless it is list or binary, repeating N times using lists:duplicate(N, W) is O(N) operation and it consumes O(N) additional memory ie whole memory is O(N+W) . If you would do flattening it would take O(N*W) time and it consumes O(N*W) memory.

Example: you can make 2^31 long list of x using this (Do not enter it in shell!):

lists:foldl(fun(_, X) -> [X|X] end, "x", lists:seq(1, 30)).

And it will take 30 times of time of [_|_] operation and consumes 31*2*8B ie 496B of memory (on 64b platform and a half on 32b). If you would do it as binary it would take over 2GB of memory and 32GB as a flat list (on 64b and 16GB on 32b). Good luck with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM