Are strings cached?

Posted on

Question :

Are strings cached?
>>> a = "zzzzqqqqasdfasdf1234"
>>> b = "zzzzqqqqasdfasdf1234"
>>> id(a)
4402117560
>>> id(b)
4402117560

but

>>> c = "!@#$"
>>> d = "!@#$"
>>> id(c) == id(d)
False
>>> id(a) == id(b)
True

Why get same id() result only when assign string?

Edited: I replace “ascii string” with just “string”. Thanks for feedback

Asked By: dohvis

||

Answer #1:

It’s not about ASCII vs. non-ASCII (your “non-ASCII” is still ASCII, it’s just punctuation, not alphanumeric). CPython, as an implementation detail, interns string constants that contain only “name characters”. “Name characters” in this case means the same thing as the regex escape w: Alphanumeric, plus underscore.

Note: This can change at any time, and should never be relied on, it’s just an optimization they happen to use.

At a guess, this choice was made to optimize code that uses getattr and setattr, dicts keyed by a handful of string literals, etc., where interning means that the dictionary lookups involved often ends up doing pointer comparisons and avoiding comparing the strings at all (when two strings are both interned, they are definitionally either the same object, or not equal, so you can avoid reading their data entirely).

Answered By: ShadowRanger

Leave a Reply

Your email address will not be published. Required fields are marked *