Issue 1493701: Performance enhancements for struct module (original) (raw)
This patch refactors the struct module to work like the re module: compile and cache the format in advance. This seems to yield at least a 20% performance improvement on Mac OS X i386, depending on the length of the format string.
$ ./python-orig/_build/python.exe -mtimeit -s "import struct; s = '\x00'
- 16" "struct.unpack('>iId', s); struct.unpack('iId', s); struct.unpack('<iId', s)" 100000 loops, best of 3: 4.48 usec per loop
$ ./bippolito-newstruct/_build/python.exe -mtimeit -s "import struct; s = '\x00' * 16" "struct.unpack('>iId', s); struct.unpack('iId', s); struct.unpack('<iId', s)" 100000 loops, best of 3: 3.54 usec per loop
It also adds a struct.Struct type, which is even faster to use than the pack/ unpack/calcsize functions since it doesn't need to look anything up in the cache.