|
| 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 | + super().__init__(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 | +extended_list = StringList_list(init_data) |
| 48 | +list_extend = ( |
| 49 | + min( |
| 50 | + timeit.repeat( |
| 51 | + stmt="extended_list.extend(init_data)", |
| 52 | + number=5, |
| 53 | + repeat=2, |
| 54 | + globals=globals(), |
| 55 | + ) |
| 56 | + ) |
| 57 | + * 1e6 |
| 58 | +) |
| 59 | + |
| 60 | +extended_user_list = StringList_UserList(init_data) |
| 61 | +user_list_extend = ( |
| 62 | + min( |
| 63 | + timeit.repeat( |
| 64 | + stmt="extended_user_list.extend(init_data)", |
| 65 | + number=5, |
| 66 | + repeat=2, |
| 67 | + globals=globals(), |
| 68 | + ) |
| 69 | + ) |
| 70 | + * 1e6 |
| 71 | +) |
| 72 | + |
| 73 | +print(f"StringList_list().extend() time: {list_extend:.2f} μs") |
| 74 | +print(f"StringList_UserList().extend() time: {user_list_extend:.2f} μs") |
0 commit comments