Why list and dict constructor is slower than list and dict literals?

Posted by Afsal on 11-Feb-2022

Hi Pythonistas!

Today, we are going to check another performance improvement tip in Python. The topic of discussion is “Why list and dict constructor is slower than list and dict literals (ie [], {})”. Let us look at the below example.

Example 1

import timeit

def using_list_literal():
    data = []
    data.append(1)
    data.append(2)
    data.append(3)
    return data
def using_list_constructor():
    data = list()
    data.append(1)
    data.append(2)
    data.append(3)
    return data

time_taken_i = timeit.timeit(using_list_literal, number=1000000)
print("The time taken for list literal: ", time_taken_i)

time_taken_e = timeit.timeit(using_list_constructor, number=1000000)
print("The time taken for list constructor: ", time_taken_e)

Output

The time taken for list literal:  0.1426095289971272
The time taken for list constructor:  0.15351822999946307

Example 2

import timeit

def using_dict_literal():
    data = {}
    data["a"] = 1
    data["b"] = 2
    data["c"] = 3
    return data
def using_dict_constructor():
    data = dict()
    data["a"] = 1
    data["b"] = 2
    data["c"] = 3
    return data

time_taken_i = timeit.timeit(using_dict_literal, number=1000000l)
print("The time taken for dict literal: ", time_taken_i)

time_taken_e = timeit.timeit(using_dict_constructor, number=1000000)
print("The time taken for dict constuctor", time_taken_e)

Output

The time taken for dict  literal:  0.14791480799976853
Time taken for dict  constructor: 0.15187519499886548

In both the examples we can see that for 1 million iterations literal has a slight advantage over the constructor.

The reason

When we analyze the internals of using_list_constructor and using_dict_constructor we can see that an extra function call is invoked. But in the case of literals, there is no function call as such. It creates a list directly.

Which is better?

Well, the answer is obvious. Using literal is faster and it is a more pythonic way of doing it.

Tip

Use the literal way of creating list and dict in code.

Hope you have learned something from this post. Please share your suggestion with afsal@parseltongue.co.in