Arrays implementation in erlang

前端 未结 2 1232
挽巷
挽巷 2021-01-19 07:51

My question is, how are arrays implemented in Erlang, as opposed to lists.

With immutable types doing things like,

move ([X | Xs], Ys) ->
    [X          


        
相关标签:
2条回答
  • 2021-01-19 08:10

    You can find the source code here. It looks like, as @rvirding mentioned, that an array is a functional tree. I haven't studied the implementation deeply--and there's no reference in the source to the data-structure's origin--but a quick skim suggests a lookup worst-case is some logarithmic factor of N.

    I'd love a correction if someone else is more familiar with this source / has a moment to study it.

    0 讨论(0)
  • 2021-01-19 08:19

    To (hopefully) clear things up a little. Remember that in Erlang ALL data is immutable! This profoundly affects how you manipulate data.

    The array module builds a structure of nested tuples where all the array slots containing data are at the same level. The size of each tuple is 10 so for array access we have O(lg10(N)). Using nested structure like this is common in languages with immutable data. You could keep an array in a flat tuple which would give you fast reads, but writes would become slow and memory hogging for large arrays/tuples as every write would entail creating a new tuple. Using a tree structure means that much less data is created in a write.

    How your move/2 function affects memory usage depends a little on whether you are writing to a used or unused slot in the array. If the slot is already in use then the resultant memory usage will be the same. If you are writing to a previously unused slot then you may need to grow the array which mean that more memory will be used.

    This is exactly the same as for your list case.

    It also depends on whether there are any remaining references to the old data structure.

    0 讨论(0)
提交回复
热议问题