2

I have 3 object Item1, Item2 and a custom iterator. Item2 is same as Item1 but it implements one more function __iter__() than Item1, __iter__() will return a custom iterator.

class Item1():
    def __init__(self, stop):
        self.stop = stop

    def __len__(self):
        return self.stop - 1

    def __getitem__(self, index):

        if index < self.stop:
            return index + 1
        raise IndexError


class Item2():
    def __init__(self, stop):
        self.stop = stop

    def __len__(self):
        return self.stop - 1

    def __getitem__(self, index):

        if index < self.stop:
            return index + 1
        raise IndexError

    def __iter__(self):
        iterator = MyIterator(self.stop)
        return iterator


class MyIterator:
    def __init__(self, max_num):
        self.max_num = max_num
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        self.index += 1
        if self.index <= self.max_num:
            return self.index
        else:
            raise StopIteration

When I use for loop to iterate Item1 and Item2, will get same results. But, I want to know the usage of memory will be the same ? Does the Item2 have the advantage of iterator?

Item1 = Item1(100000)
item2 = Item2(100000)

for item in item1:
    print(item)

for item in item2:
    print(item)
bear
  • 43
  • 4

1 Answers1

5

You can check the memory usage via tracemalloc()

https://medium.com/survata-engineering-blog/monitoring-memory-usage-of-a-running-python-program-49f027e3d1ba

memory usage of your implementation on my machine:

item1: Current memory usage is 0.000379MB; Peak was 0.000593MB

item2: Current memory usage is 0.001218MB; Peak was 0.001478MB

item2 needs more memory

->here is a post about the difference What's the difference between __iter__ and __getitem__?

Roman
  • 176
  • 10