问题
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 itO(n)orO(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