Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #82909

Re: question on string object handling in Python 2.7.8

From Gregory Ewing <greg.ewing@canterbury.ac.nz>
Newsgroups comp.lang.python
Subject Re: question on string object handling in Python 2.7.8
Date 2014-12-25 17:23 +1300
Message-ID <cg1hq4Fan2mU1@mid.individual.net> (permalink)
References <mailman.17176.1419410409.18130.python-list@python.org>

Show all headers | View raw


Dave Tian wrote:

> A: a = ‘h’ 
 > B: b = ‘hh’
> 
> According to me understanding, A should be faster as characters would
> shortcut this 1-byte string ‘h’ without malloc;

It sounds like you're expecting characters to be stored
"unboxed" like in Java.

That's not the way Python works. Objects are used for
everything, including numbers and characters (there is
no separate character type in Python, they're just
length-1 strings).

 > for i in range(0, 100000000):
 >	a = ‘h’ #or b = ‘hh’
 > Testing cmd: python -m cProfile test.py

Since you're assigning a string literal, there's just
one string object being allocated (at the time the code
is read in and compiled). All the loop is doing is
repeatedly assigning a reference to that object to a
or b, which doesn't require any further mallocs;
all it does is adjust reference counts. This will
be swamped by the overhead of the for-loop itself,
which is allocating and deallocating 100 million
integer objects.

I would expect both of these to be exactly the same
speed, within measurement error. Any difference you're
seeing is probably just noise, or the result of some
kind of warming-up effect.

-- 
Greg

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

question on string object handling in Python 2.7.8 Dave Tian <dave.jing.tian@gmail.com> - 2014-12-23 20:28 -0500
  Re: question on string object handling in Python 2.7.8 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-12-24 22:22 +1100
    Re: question on string object handling in Python 2.7.8 Ian Kelly <ian.g.kelly@gmail.com> - 2014-12-24 09:39 -0700
  Re: question on string object handling in Python 2.7.8 Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2014-12-25 17:23 +1300
  Re: question on string object handling in Python 2.7.8 Denis McMahon <denismfmcmahon@gmail.com> - 2014-12-25 16:34 +0000

csiph-web