Is empty string cached?

Peter Hansen peter at engcorp.com
Thu Feb 16 09:38:59 EST 2006


Farshid Lashkari wrote:
> However, the following commands add to my confusion:
> 
>  >> a = 'wtf?'
>  >> b = 'wtf?'
>  >> a is b
> False
> 
> So how are string literals cached? Is there an explanation somewhere? Is 
> it some freaky voodoo, and I should just assume that a string literal 
> will always generate a new object?

A few comments (which I hope are correct, but which I hope you will read 
then mostly ignore since you probably shouldn't be designing based on 
this stuff anyway):

1. What you see at the interactive prompt is not necessarily what will 
happen in a compiled source file.  Try the above test with and without 
the question mark both at the interactive prompt and in source and see.

2. The reason for the difference with ? is probably due to an 
optimization relating to looking up attribute names and such in 
dictionaries.  wtf? is not a valid attribute, so it probably isn't 
optimized the same way.

2.5. I think I had a third comment like the above but after too little 
sleep last night it seems it's evaporated since I began writing...

3. As Steve or someone said, these things are implementation details 
unless spelled out explicitly in the language reference, so don't rely 
on them.

4. If you haven't already written your code and profiled and found it 
lacking in performance and proving that the cause is related to whether 
or not you hoisted the string literal out of the loop, you're wasting 
your time and this is a good opportunity to begin reprogramming your 
brain not to optimize prematurely.  IMHO.  FWIW. :-)

-Peter




More information about the Python-list mailing list