python的list的append方法的性能问题

作为客户端while true来循环接受server端推过来的数据,同时将这些数据append到一个list里面,不断更新。由于数据较多,我发现用append方法好像会占用cpu的30%-40%(通过top指令)。我现在想会不会是动态数组扩容的机制,导致了python内部会因为数组长度不够而重新分配一块更大的内存来给list扩容,这样就会产生copy,从而导致性能降低。但这个只是猜测,你们说有没有别的方法来代替append,或者直接给list定义为定长的?不知道这两种方法哪个可行,放假期间没法连接公司的server进行试验,但是想先问问看大家,有没有啥好思路?多谢了

阅读 12.3k
1 个回答

Iterating through the multiple calls to append adds to the complexity, making it equivalent to that of extend, and since extend's iteration is implemented in C, it will always be faster if you intend to append successive items from an iterable onto a list

结论:
extend要高效于append。

append vs extend

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题