Performance of list(…).insert(…)

后端 未结 3 1571
刺人心
刺人心 2021-01-01 22:24

I thought about the following question about computer\'s architecture. Suppose I do in Python

from bisect import bisect
index = bisect(x, a)      # O(log n)          


        
3条回答
  •  生来不讨喜
    2021-01-01 23:08

    CPython lists are contiguous arrays. Which one of the O(log n) bisect and O(n) insert dominates your performance profile depends on the size of your list and also the constant factors inside the O(). Particularly, the comparison function invoked by bisect can be something expensive depending on the type of objects in the list.

    If you need to hold potentially large mutable sorted sequences then the linear array underlying Pythons list type isn't a good choice. Depending on your requirements heaps, trees or skip-lists might be appropriate.

提交回复
热议问题