Python list.clear complexity

你离开我真会死。 提交于 2020-01-04 02:35:10

问题


What is the complexity of the Python 3 method list.clear() ?

  • It is not given here: https://wiki.python.org/moin/TimeComplexity

  • In the documentation it is said to be equivalent with del a[:], but I do not know the complexity of this function itself. Is it O(n) or O(1) ?

  • I took a look in listobject.c. Found this.

    int
    PyList_ClearFreeList(void)
    {
        PyListObject *op;
        int ret = numfree;
        while (numfree) {
            op = free_list[--numfree];
            assert(PyList_CheckExact(op));
            PyObject_GC_Del(op);
        }
        return ret;
    }
    

    Here it seems like O(n), but I am not sure if this is the right code.

I am developing a program with performance needs, where a list is repeatedly filled and emptied, I am trying to find the best way to empty it (Since there is only one way to fill it).

If this function is O(n), I will just create a new list every time, which has it's own cost, but I don't know a better way.

Another issue crossed my mind is that Python has a garbage collector, so if I don't free these objects(create new lists every time, leaving the other unattended by reassigning the variable name), Python does the deletion in the background(I am not sure about this information), so I won't gain speed applying any of the methods above because result is the same.

Any knowledge is appreciated. Thanks.

来源:https://stackoverflow.com/questions/46985483/python-list-clear-complexity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!