|
| 1 | +import timeit |
| 2 | +from collections import UserList |
| 3 | + |
| 4 | + |
| 5 | +class StringList_list(list): |
| 6 | + def __init__(self, iterable): |
| 7 | + super().__init__(str(item) for item in iterable) |
| 8 | + |
| 9 | + def __setitem__(self, index, item): |
| 10 | + super().__setitem__(index, str(item)) |
| 11 | + |
| 12 | + def insert(self, index, item): |
| 13 | + super().insert(index, str(item)) |
| 14 | + |
| 15 | + def append(self, item): |
| 16 | + super().append(str(item)) |
| 17 | + |
| 18 | + def extend(self, other): |
| 19 | + if isinstance(other, type(self)): |
| 20 | + super().extend(other) |
| 21 | + else: |
| 22 | + super().extend(str(item) for item in other) |
| 23 | + |
| 24 | + |
| 25 | +class StringList_UserList(UserList): |
| 26 | + def __init__(self, iterable): |
| 27 | + self.data = [str(item) for item in iterable] |
| 28 | + |
| 29 | + def __setitem__(self, index, item): |
| 30 | + self.data[index] = str(item) |
| 31 | + |
| 32 | + def insert(self, index, item): |
| 33 | + self.data.insert(index, str(item)) |
| 34 | + |
| 35 | + def append(self, item): |
| 36 | + self.data.append(str(item)) |
| 37 | + |
| 38 | + def extend(self, other): |
| 39 | + if isinstance(other, type(self)): |
| 40 | + self.data.extend(other) |
| 41 | + else: |
| 42 | + self.data.extend(str(item) for item in other) |
| 43 | + |
| 44 | + |
| 45 | +init_data = range(10000) |
| 46 | + |
| 47 | +list_initialization = min( |
| 48 | + timeit.repeat( |
| 49 | + stmt="StringList_list(init_data)", |
| 50 | + number=1000, |
| 51 | + repeat=5, |
| 52 | + globals=globals(), |
| 53 | + ) |
| 54 | +) |
| 55 | + |
| 56 | +user_list_initialization = min( |
| 57 | + timeit.repeat( |
| 58 | + stmt="StringList_UserList(init_data)", |
| 59 | + number=1000, |
| 60 | + repeat=5, |
| 61 | + globals=globals(), |
| 62 | + ) |
| 63 | +) |
| 64 | + |
| 65 | +print( |
| 66 | + f"list is {list_initialization / user_list_initialization:.3f}", |
| 67 | + "times slower than UserList", |
| 68 | +) |
| 69 | + |
| 70 | + |
| 71 | +extended_list = StringList_list(init_data) |
| 72 | +list_extend = min( |
| 73 | + timeit.repeat( |
| 74 | + stmt="extended_list.extend(init_data)", |
| 75 | + number=5, |
| 76 | + repeat=2, |
| 77 | + globals=globals(), |
| 78 | + ) |
| 79 | +) |
| 80 | + |
| 81 | +extended_user_list = StringList_UserList(init_data) |
| 82 | +user_list_extend = min( |
| 83 | + timeit.repeat( |
| 84 | + stmt="extended_user_list.extend(init_data)", |
| 85 | + number=5, |
| 86 | + repeat=2, |
| 87 | + globals=globals(), |
| 88 | + ) |
| 89 | +) |
| 90 | + |
| 91 | +print( |
| 92 | + f"list is {list_extend / user_list_extend:.3f}", |
| 93 | + "times slower than UserList", |
| 94 | +) |
0 commit comments