0

I am creating a Python class to represent a Geographic Position. Its main goal is to store latitude, longitude, elevation, so it is going to be used much like a C# "struct", a value type that is supposed to have lots of instances at runtime.

I am considering adding some methods to that class (__str__ would be one), and I wonder if adding methods to a class has any impact on the performance.

Performance metrics I am interested on are the following:

  • Object creation overhead;
  • Memory overhead (when lots of instances are created)
  • Speed of manipulation of the class even when the "extra methods" are not called.

For example, I read that __slots__ is useful in some contexts because by default the __dict__ attribute ends up eating some space on each instance.

So que question is:

Which impacts are supposed to exist if I have a class with a large amount of methods?

Or pragmatically speaking:

Is adding more and more methods to a class that is supposed to be lightweight something I should try to avoid for any reason?

Ralf Haring
  • 1,253
  • 1
  • 10
  • 18
heltonbiker
  • 26,657
  • 28
  • 137
  • 252

1 Answers1

2

What performance are you worried about? Memory? Attribute access? You need to define your parameters more clearly.

Methods are just another type of attribute; lookups fall through the instance to the class object if the instance doesn't define the attribute. Looking up existing instance attributes is not really affected by what attributes are available on the class*.

Because methods are attributes of the class, memory performance isn't really affected by them; you can have 1000 or 10000 instances and there is still going to be just the one method on the class.

If you care about memory performance, you should be using slots for your objects. Slots don't make attribute access faster either, they only save on the memory footprint.

So, to summarize:

  • Methods don't affect attribute lookup performance on instances. instance.latitude access is not going to be any faster or slower because the class has an extra method.

  • Methods don't affect memory performance; the class object holds the method, not the instances. If you are worried about memory footprint, use __slots__ for your attributes.


*Technically speaking, Python does look for data descriptors on the class, always, when looking for an attribute. Because class attributes are backed by a dictionary, that is a O(1) constant time lookup, on average. You'd have to create a catastrophic chain of hash conflicts for that to ever affect performance. See the descriptor howto for details.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks, I edited the question, which incidentally covers the very topics you already pointed out. Thanks for now! – heltonbiker Jun 08 '14 at 15:42