Why are lists used infrequently in Go?

前端 未结 7 1289
眼角桃花
眼角桃花 2021-01-30 07:57

I\'m new to Go, and quite excited about it. But, in all the languages I\'ve worked with extensively: Delphi, C#, C++, Python - Lists are very important because they can be dynam

7条回答
  •  生来不讨喜
    2021-01-30 08:26

    From: https://groups.google.com/forum/#!msg/golang-nuts/mPKCoYNwsoU/tLefhE7tQjMJ

    
    It depends a lot on the number of elements in your lists,
     whether a true list or a slice will be more efficient
     when you need to do many deletions in the 'middle' of the list.
    
    #1
    The more elements, the less attractive a slice becomes. 
    
    #2
    When the ordering of the elements isn't important,
     it is most efficient to use a slice and
     deleting an element by replacing it by the last element in the slice and
     reslicing the slice to shrink the len by 1
     (as explained in the SliceTricks wiki)
    

    So
    use slice
    1. If order of elements in list is Not important, and you need to delete, just
    use List swap the element to delete with last element, & re-slice to (length-1)
    2. when elements are more (whatever more means)


    There are ways to mitigate the deletion problem --
    e.g. the swap trick you mentioned or
    just marking the elements as logically deleted.
    But it's impossible to mitigate the problem of slowness of walking linked lists.
    

    So
    use slice
    1. If you need speed in traversal

提交回复
热议问题