Complexity of len() with regard to sets and lists

前端 未结 7 1304
耶瑟儿~
耶瑟儿~ 2021-02-04 23:38

The complexity of len() with regards to sets and lists is equally O(1). How come it takes more time to process sets?

~$ python -m timeit \"a=[1,2,3,         


        
7条回答
  •  误落风尘
    2021-02-05 00:04

    The relevant lines are http://svn.python.org/view/python/trunk/Objects/setobject.c?view=markup#l640

    640     static Py_ssize_t
    641     set_len(PyObject *so)
    642     {
    643         return ((PySetObject *)so)->used;
    644     }
    

    and http://svn.python.org/view/python/trunk/Objects/listobject.c?view=markup#l431

    431     static Py_ssize_t
    432     list_length(PyListObject *a)
    433     {
    434         return Py_SIZE(a);
    435     }
    

    Both are only a static lookup.

    So what is the difference you may ask. You measure the creation of the objects, too. And it is a little more time consuming to create a set than a list.

提交回复
热议问题