python 字节数组在哪里使用? [英] Where are python bytearrays used?

查看:26
本文介绍了python 字节数组在哪里使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在 python 中遇到了名为 bytearray 的数据类型.有人可以提供需要字节数组的场景吗?

I recently came across the dataType called bytearray in python. Could someone provide scenarios where bytearrays are required?

推荐答案

bytearray 非常类似于常规的 python 字符串(python2.x 中的strbytes in python3) 但有一个重要的区别,而字符串是不可变的bytearray是可变的,有点像list 单个字符串.

A bytearray is very similar to a regular python string (str in python2.x, bytes in python3) but with an important difference, whereas strings are immutable, bytearrays are mutable, a bit like a list of single character strings.

这很有用,因为某些应用程序使用字节序列的方式对不可变字符串表现不佳.当您在大块内存中进行大量小的更改时,例如在数据库引擎或图像库中,字符串的性能非常差;因为您必须复制整个(可能很大)的字符串.bytearray 的优点是无需先复制内存即可进行此类更改.

This is useful because some applications use byte sequences in ways that perform poorly with immutable strings. When you are making lots of little changes in the middle of large chunks of memory, as in a database engine, or image library, strings perform quite poorly; since you have to make a copy of the whole (possibly large) string. bytearrays have the advantage of making it possible to make that kind of change without making a copy of the memory first.

但这种特殊情况实际上更多的是例外,而不是规则.大多数用途涉及比较字符串或字符串格式.对于后者,无论如何通常都有一个副本,因此可变类型不会提供任何优势,而对于前者,由于不可变字符串无法更改,您可以计算字符串的 hash 并将其作为一个比较按顺序比较每个字节的快捷方式,这几乎总是一个大胜利;所以它是默认的不可变类型(strbytes);当您需要它的特殊功能时,bytearray 是例外.

But this particular case is actually more the exception, rather than the rule. Most uses involve comparing strings, or string formatting. For the latter, there's usually a copy anyway, so a mutable type would offer no advantage, and for the former, since immutable strings cannot change, you can calculate a hash of the string and compare that as a shortcut to comparing each byte in order, which is almost always a big win; and so it's the immutable type (str or bytes) that is the default; and bytearray is the exception when you need it's special features.

这篇关于python 字节数组在哪里使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆