最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How does int() operate from memoryview -- does it create an intermediate bytes copy? - Stack Overflow

programmeradmin1浏览0评论

I'm very interested in zero-copy operations (and disappointed that memoryview doesn't have all the member functions that bytes does). My application will be pretty intensive in this regard.

Consider this python code, extracting integers from bytes/buffers:

>>>
>>> b: bytes = b'987654'
>>> mv: memoryview = memoryview(b)
>>> type(mv)
<class 'memoryview'>
>>> isinstance(mv, bytes)
False
>>> int(b) # as expected
987654
>>> int(mv) # works in py 3.12, but does it make a temporary bytes copy?
987654

Doing a huge number of these operations, it will make a big difference if it's making intermediate/temporary bytes copies for each integer extraction.

  • Which int() constructor gets called?
  • What's a good test for me to determine/verify this? I'm thinking some monkeypatch of mv.__some_member_function__ = my_function_that_prints_something but where to start?
  • And, of course, is an intermediate bytes copy being made just for the int() call?

My environment:

>>> import sys
>>> sys.version
'3.12.9 (main, Feb  6 2025, 14:33:23)  [GCC 14.2.0 64 bit (AMD64)]'

Reference:

  • Python's int() docs
  • What exactly is the point of memoryview in Python?
发布评论

评论列表(0)

  1. 暂无评论