Why does awk seem to randomize the array?

前端 未结 4 829
忘了有多久
忘了有多久 2020-11-29 12:36

If you look at output of this awk test, you see that array in awk seems to be printed at some random pattern. It seems to be in same o

4条回答
  •  日久生厌
    2020-11-29 13:12

    Awk uses hash tables to implement associative arrays. This is just an inherent property of this particular data structure. The location that a particular element is stored into the array depends on the hash of the value. Other factors to consider is the implementation of the hash table. If it is memory efficient, it will limit the range each key gets stored in using the modulus function or some other method. You also may get clashing hash values for different keys so chaining will occur, again affecting the order depending on which key was inserted first.

    The construct (key in array) is perfectly fine when used appropriately to loop over every key but you cannot count on the order and you should not update array whilst in the loop as you may end up process array[key] multiple times by mistake.

    There is a good decription of hash tables in the book Think Complexity.

提交回复
热议问题