# HG changeset patch # User Stefan Behnel # Date 1321635579 -3600 # Node ID 0902c555678135115eb50c0ffc0576b8f551f5e4 # Parent 7992f32474476a38e7030b0b39e323e9041b66a6 implement a simple one instance cache for slices to speed up slice creation (see ticket 10227 for benchmarks) diff -r 7992f3247447 -r 0902c5556781 Include/pythonrun.h --- a/Include/pythonrun.h Fri Nov 18 13:52:37 2011 +0200 +++ b/Include/pythonrun.h Fri Nov 18 17:59:39 2011 +0100 @@ -211,6 +211,7 @@ PyAPI_FUNC(void) PyFloat_Fini(void); PyAPI_FUNC(void) PyOS_FiniInterrupts(void); PyAPI_FUNC(void) _PyGC_Fini(void); +PyAPI_FUNC(void) PySlice_Fini(void); PyAPI_DATA(PyThreadState *) _Py_Finalizing; #endif diff -r 7992f3247447 -r 0902c5556781 Objects/sliceobject.c --- a/Objects/sliceobject.c Fri Nov 18 13:52:37 2011 +0200 +++ b/Objects/sliceobject.c Fri Nov 18 17:59:39 2011 +0100 @@ -80,19 +80,38 @@ }; -/* Slice object implementation +/* Slice object implementation */ - start, stop, and step are python objects with None indicating no +/* Using a cache is very effective since typically only a single slice is + * created and then deleted again + */ +static PySliceObject *slice_cache = NULL; +void PySlice_Fini(void) +{ + PySliceObject *obj = slice_cache; + if (obj != NULL) { + slice_cache = NULL; + PyObject_Del(obj); + } +} + +/* start, stop, and step are python objects with None indicating no index is present. */ PyObject * PySlice_New(PyObject *start, PyObject *stop, PyObject *step) { - PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type); - - if (obj == NULL) - return NULL; + PySliceObject *obj; + if (slice_cache != NULL) { + obj = slice_cache; + slice_cache = NULL; + _Py_NewReference((PyObject *)obj); + } else { + obj = PyObject_New(PySliceObject, &PySlice_Type); + if (obj == NULL) + return NULL; + } if (step == NULL) step = Py_None; Py_INCREF(step); @@ -260,7 +279,10 @@ Py_DECREF(r->step); Py_DECREF(r->start); Py_DECREF(r->stop); - PyObject_Del(r); + if (slice_cache == NULL) + slice_cache = r; + else + PyObject_Del(r); } static PyObject * diff -r 7992f3247447 -r 0902c5556781 Python/pythonrun.c --- a/Python/pythonrun.c Fri Nov 18 13:52:37 2011 +0200 +++ b/Python/pythonrun.c Fri Nov 18 17:59:39 2011 +0100 @@ -531,6 +531,7 @@ PyLong_Fini(); PyFloat_Fini(); PyDict_Fini(); + PySlice_Fini(); /* Cleanup Unicode implementation */ _PyUnicode_Fini();