Skip to content

Instantly share code, notes, and snippets.

@rebornwwp
Created March 9, 2019 08:20
Show Gist options
  • Save rebornwwp/50523fb10b1e959e18acda83205a405c to your computer and use it in GitHub Desktop.
Save rebornwwp/50523fb10b1e959e18acda83205a405c to your computer and use it in GitHub Desktop.
Less copies in Python with the buffer protocol and memoryviews
# Snippet #2
f = open(FILENAME, 'rb')
data = bytearray(f.read())
data[0] = 97 # OK!
# Snippet #3
f = open(FILENAME, 'rb')
data = bytearray(os.path.getsize(FILENAME))
f.readinto(data) # The result: this code runs ~30% faster than snippet #2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment