python list列表append方法的性能问题,pythonappend,作为客户端用while


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

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

编橙之家文章,

评论关闭