Why is tuple.index () similar in performance to list.index ()?

I wrote a simple function that gets what implements .index () and a list of characters to check.

My guess was that since rows and tuples are immutable, they will have similar performance (or at least the tuple will outperform the list). Instead, the tuple seems equivalent to a list. Why is this?

from string import ascii_lowercase
from random import randint
from timeit import Timer


def check_index(st, guesses):
    for i in guesses:
        st.index(i)

if __name__ == "__main__":
    num_checks = 10
    lst = [n for n in ascii_lowercase]
    st = ascii_lowercase
    tup = tuple(lst)
    guesses = [ascii_lowercase[randint(0, len(ascii_lowercase)-1)]
               for n in xrange(num_checks)]

    def run_string():
        check_index(st, guesses)

    def run_list():
        check_index(lst, guesses)

    def run_tuple():
        check_index(tup, guesses)

    t2 = Timer(run_list)
    print "List", t2.timeit()
    t3 = Timer(run_tuple)
    print "Tuple", t3.timeit()
    t = Timer(run_string)
    print "String", t.timeit()

Run Examples (Python 2.7.6)

List 5.26431703568
Tuple 5.28769207001
String 3.16058015823

List 5.30263400078
Tuple 5.17412590981
String 3.17718791962

List 5.21962976456
Tuple 5.35261583328
String 3.22652792931
+4
source share
2 answers

tl; dr: String calls indexhave a lot of optimizations under the hood and you don't have to do rich comparisons. And list, and tuplemust fulfill them; volatility does not matter.


stringobject.c, , index string_find_internal, stringlib_find_slice, stringlib_find, fastsearch.

fastsearch , , . , Boyer-Moore python. 1- , fastsearch :

    } else if (mode == FAST_SEARCH) {
        for (i = 0; i < n; i++)
            if (s[i] == p[0])
                return i;
    }

, C.

, . tuple list s?

; , :

for (i = start; i < stop && i < Py_SIZE(self); i++) {
    int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
    if (cmp > 0)
        return PyInt_FromSsize_t(i);

, ==, PyObject_RichCompareBool . ( object.c, ), , , , , , NotImplemented singleton , , .

, , index, . .

+3

index . python, . , , .

+1

Source: https://habr.com/ru/post/1540597/


All Articles