简体   繁体   English

为什么bytearray_obj.extend(bytes)与bytearray_obj + = bytes不同?

[英]Why does bytearray_obj.extend(bytes) differ from bytearray_obj += bytes?

Just saw (and enjoyed) the video of Brandon Rhodes talking on PyCon 2015 about bytearrays. 刚刚看到(并欣赏)Brandon Rhodes在PyCon 2015上讨论bytearrays的视频。

He said that .extend method is slow, but += operation is implemented differently and is much more efficient. 他说.extend方法很慢,但+=操作的实现方式不同而且效率更高。 Yes, indeed: 确实是的:

>>> timeit.timeit(setup='ba=bytearray()', stmt='ba.extend(b"xyz123")', number=1000000)
0.19515220914036036
>>> timeit.timeit(setup='ba=bytearray()', stmt='ba += b"xyz123"', number=1000000)
0.09053478296846151

What is the reason of having two ways of extending a bytearray? 有两种扩展bytearray的方法是什么原因? Are they performing exactly the same task? 他们执行完全相同的任务吗? If not, what is the difference? 如果没有,有什么区别? Which one should be used when? 应该使用哪一个?

What is the reason of having two ways of extending a bytearray? 有两种扩展bytearray的方法是什么原因?

  • An operator is not chainable like function calls, whereas a method is. 运算符不像函数调用那样可链接,而方法是。
  • The += operator cannot be used with nonlocal variables. +=运算符不能与非局部变量一起使用。
  • The += is slightly faster +=略快
  • .extend() may/might/could sometimes possibly be more readable .extend()可能/可能/有时可能更具可读性

Are they performing exactly the same task? 他们执行完全相同的任务吗?

Depends on how you look at it. 取决于你如何看待它。 The implementation is not the same, but the result usually is. 实现方式不尽相同,但结果通常是。 For a bunch of examples and explanations, maybe try the SO search, and for example this question: Concatenating two lists - difference between '+=' and extend() 对于一堆示例和解释,可以尝试SO搜索,例如这个问题: 连接两个列表 - '+ ='和extend()之间的区别

Which one should be used when? 应该使用哪一个?

If you care about the small performance difference, use the operator when you can. 如果您关心小的性能差异,请尽可能使用操作员。 Other than that, just use whichever you like to look at, of course given the restrictions I mentioned above. 除此之外,只要使用你想看的任何一个,当然考虑到我上面提到的限制。

But the main question is why += and .extend do not share the same internal function to do the actual work of extending a bytearray. 但主要的问题是为什么+ =和.extend不共享相同的内部函数来完成扩展bytearray的实际工作。

Because one is faster but has limitations, so we need the other for the cases where we do have the limitations. 因为一个更快但有限制,所以我们需要另一个我们确实有限制的情况。


Bonus : 奖金

The increment operator might cause some funny business with tuples: 增量运算符可能会导致一些有趣的业务与元组:

if you put a list in a tuple and use the += operator to extend the list, the increment succeeds and you get a TypeError 如果你在一个元组中放入一个列表并使用+ =运算符来扩展列表,那么增量会成功并且你得到一个TypeError

Source: https://emptysqua.re/blog/python-increment-is-weird-part-ii/ 资料来源: https//emptysqua.re/blog/python-increment-is-weird-part-ii/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM