Comment

Jeff Epler

It looks like Python (2.7 here) is optimizing this case by returning the original string:
>>> s = "abc"
>>> s[:50] is s
True

And here's the C code that makes it happen:
1124 static PyObject *
1125 string_slice(register PyStringObject *a, register Py_ssize_t i,
1126 register Py_ssize_t j)
...
1133 if (j > Py_SIZE(a))
1134 j = Py_SIZE(a);
1135 if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
1136 /* It's the same as a */
1137 Py_INCREF(a);
1138 return (PyObject *)a;

That said, I'd predict a measurable difference in performance, due to the extra bytecodes and the len() function call in a, at least if you're using traditional cpython.

Replies

Peter Bengtsson

Thanks for that!
Yeah maybe you could see a measurable difference but that would require a workload that vastly exaggerates the conditions of my application.