w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Which is faster Counter()+=Counter or Counter.update(Counter)?

The Counter.update() method was designed to be faster. The __add__() method does more work because it has to eliminate non-negative values:

# heart of the update() loop in Python 2:
for elem, count in iterable.iteritems():
    self[elem] = self_get(elem, 0) + count

# heart of the __add__() loop in Python 2:
result = Counter()
for elem, count in self.items():
    newcount = count + other[elem]
    if newcount > 0:
        result[elem] = newcount
for elem, count in other.items():
    if elem not in self and count > 0:
        result[elem] = count
return result

As you can see, the __add__ method does considerable more work.

There is another difference in later versions of Python 3 which have an __iadd__() method that does a true in-place update that does less work than an __add__() method which creates a new counter followed by an assignment to replace the old counter:

def __iadd__(self, other):
    for elem, count in other.items():
        self[elem] += count
    return self._keep_positive()

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.