Skip to content

Commit edb61db

Browse files
committed
Allow users to specify Packer internal buf_size
Giving this flexibility to users means that internal reallocations can be avoided if the buffer size is good enough, at the expense of potentially allocating more memory than needed. This, together with reusing a Packer object, means that multiple serialisations can end up requiring no memory allocations other than the initial buffer creation, which can be a big win in some situations. The default value is still 1MB, making this backwards compatible. Signed-off-by: Rodrigo Tobar <[email protected]>
1 parent c8d0751 commit edb61db

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

msgpack/_packer.pyx

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,11 @@ cdef class Packer(object):
102102
:param str unicode_errors:
103103
The error handler for encoding unicode. (default: 'strict')
104104
DO NOT USE THIS!! This option is kept for very specific usage.
105+
106+
:param int buf_size:
107+
The size of the internal buffer. (default: 1024 * 1024)
108+
Useful if serialisation size can be correctly estimated,
109+
avoid unnecessary reallocations.
105110
"""
106111
cdef msgpack_packer pk
107112
cdef object _default
@@ -112,8 +117,7 @@ cdef class Packer(object):
112117
cdef bint autoreset
113118
cdef bint datetime
114119

115-
def __cinit__(self):
116-
cdef int buf_size = 1024*1024
120+
def __cinit__(self, buf_size=1024*1024, **_kwargs):
117121
self.pk.buf = <char*> PyMem_Malloc(buf_size)
118122
if self.pk.buf == NULL:
119123
raise MemoryError("Unable to allocate internal buffer.")
@@ -122,7 +126,7 @@ cdef class Packer(object):
122126

123127
def __init__(self, *, default=None,
124128
bint use_single_float=False, bint autoreset=True, bint use_bin_type=True,
125-
bint strict_types=False, bint datetime=False, unicode_errors=None):
129+
bint strict_types=False, bint datetime=False, unicode_errors=None, buf_size=1024*1024):
126130
self.use_float = use_single_float
127131
self.strict_types = strict_types
128132
self.autoreset = autoreset

0 commit comments

Comments
 (0)