Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How efficient is Python substring extraction?

I've got the entire contents of a text file (at least a few KB) in string myStr.

Will the following code create a copy of the string (less the first character) in memory?

myStr = myStr[1:]

I'm hoping it just refers to a different location in the same internal buffer. If not, is there a more efficient way to do this?

Thanks!

Note: I'm using Python 2.5.

like image 564
Cameron Avatar asked Jan 22 '23 10:01

Cameron


1 Answers

At least in 2.6, slices of strings are always new allocations; string_slice() calls PyString_FromStringAndSize(). It doesn't reuse memory--which is a little odd, since with invariant strings, it should be a relatively easy thing to do.

Short of the buffer API (which you probably don't want), there isn't a more efficient way to do this operation.

like image 145
Glenn Maynard Avatar answered Jan 29 '23 23:01

Glenn Maynard