I recently compared the processing speeds of []
and list()
and was surprised to discover that []
runs more than three times faster than list()
. I ran the same test with {}
and dict()
and the results were practically identical: []
and {}
both took around 0.128sec / million cycles, while list()
and dict()
took roughly 0.428sec / million cycles each.
Why is this? Do []
and {}
(and probably ()
and ''
, too) immediately pass back a copies of some empty stock literal while their explicitly-named counterparts (list()
, dict()
, tuple()
, str()
) fully go about creating an object, whether or not they actually have elements?
I have no idea how these two methods differ but I’d love to find out.
I couldn’t find an answer in the docs or on SO, and searching for empty brackets turned out to be more problematic than I’d expected.
I got my timing results by calling timeit.timeit("[]")
and timeit.timeit("list()")
, and timeit.timeit("{}")
and timeit.timeit("dict()")
, to compare lists and dictionaries, respectively. I’m running Python 2.7.9.
I recently discovered “Why is if True slower than if 1?” that compares the performance of if True
to if 1
and seems to touch on a similar literal-versus-global scenario; perhaps it’s worth considering as well.