Python Forum

Full Version: Getting rid of old string values
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Recently I posted something here, can't remember exactly which thread, in which I started with an empty string and kept adding bits to it.

deanhystad pointed out, because strings are immutable, I would end up with a lot of strings hanging around in memory. Python doesn't overwrite them. I don't know what happens to them or how Python deals with them.

I was thinking of that today. I get a date from Excel, like 2022-05-21 04:33:27 and put it in this function:

def string2Seconds(date):
    st = str(date)
    # need to specify the format of the string
    dt = datetime.strptime(st, "%Y-%m-%d %H:%M:%S")
    # convert dt to epoch seconds
    seconds = dt.timestamp()
    return seconds
Maybe I am looking for all rows in the Excel after 2022-05-21 04:33:27 or before 2022-05-21 04:33:27

That would leave a lot of old st variables hanging around in memory.

Is there anything I can do about that??
I don't understand the problem. The st variables are local variables. They are returned to the garbage collector when the function exits. They wont "hang in memory".
Carbage collector works based on reference count. So non-referenced objects (of string) will be destroyed.

The real problem with concatenating strings is it's quadratic runtime cost. From Python documentation:

Quote:Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

  • if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete
  • if concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism
  • if concatenating tuple objects, extend a list instead
  • for other types, investigate the relevant class documentation
Thanks for your replies.

OK, I obviously misunderstood deanhystad.

Unreferenced variables will be trashed when a function exits. Use lists if you can.

Got it!