From 4d09d07e731d0454bf9f103ba486f06edcc6c2df Mon Sep 17 00:00:00 2001 Message-Id: <4d09d07e731d0454bf9f103ba486f06edcc6c2df.1719203452.git.mdw@distorted.org.uk> From: Mark Wooding Date: Fri, 9 Nov 2018 12:27:42 +0000 Subject: [PATCH] bytestring.c: Cache empty and singleton strings. Organization: Straylight/Edgeware From: Mark Wooding --- bytestring.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/bytestring.c b/bytestring.c index 8557e3b..124ae9a 100644 --- a/bytestring.c +++ b/bytestring.c @@ -32,6 +32,8 @@ PyTypeObject *bytestring_pytype; +static PyObject *empty, *bytev[256]; + static PyObject *allocate(PyTypeObject *ty, size_t n) { PyStringObject *x; @@ -47,6 +49,18 @@ static PyObject *allocate(PyTypeObject *ty, size_t n) static PyObject *dowrap(PyTypeObject *ty, const void *p, size_t n) { PyObject *x; + int ch; + + if (p && ty == bytestring_pytype) { + if (!n) { + if (!empty) empty = allocate(ty, 0); + Py_INCREF(empty); return (empty); + } else if (n == 1 && (ch = *(unsigned char *)p) < sizeof(bytev)) { + if (!bytev[ch]) + { bytev[ch] = allocate(ty, 1); *PyString_AS_STRING(bytev[ch]) = ch; } + Py_INCREF(bytev[ch]); return (bytev[ch]); + } + } x = allocate(ty, n); if (p) memcpy(PyString_AS_STRING(x), p, n); -- [mdw]