Why don't Bash associative arrays maintain index order?

前端 未结 3 915
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 06:28

I\'m creating associative arrays to process in a for loop but i\'m getting some strange results in index order. Please take a look at this example script:

#!         


        
3条回答
  •  天命终不由人
    2021-01-14 06:50

    Why order of items is changing?

    Because generally associative arrays don't naturally maintain insertion orders: tree-based ones use natural (sorted) ordering and hashmaps use wherever their hash function lands the keys (which can be randomised per-process or even per-map for security reasons).

    The latter also explains why the order of items can even change as you add new items: not only can new items get inserted between existing ones, when the hashmap has to get resized the entire sequence will get "reshuffled" as the entries are rehashed and moved to their new position.

    There are languages which either explicitly add ordering as a feature (generally using a doubly linked list), or use a naturally ordered hashmap, in which case insertion order is maintained, but you can't assume this property holds unless the language guarantees it. Which bash does not.

提交回复
热议问题