Classes or closures for simple things in Python
I would like to know more about the functions "with memory" implemented as classes vs closures.
Consider the (very) simple example:
def constant(value):
def _inner():
return value
return _inner
x = constant(5)
print(x())
vs.
class Constant():
def __init__(self, value):
self._value = value
def __call__(self):
return self._value
y = Constant(5)
print(y())
Is the performance and memory consumption of any of these better? Using slots will make the class perform better?
Thanks,
Hernan
Ps.- I know that in this extremely simple example, probably it does not matter. But I am interested in more complex functions that will be called a big number of times or t开发者_运维知识库hat will be instantiated many times.
In Python 2.6 I get the following:
def foo(x):
def bar():
return x
return bar
b = foo(4)
b.__sizeof__()
>>> 44
But using a class:
class foo(object):
def __init__(self,x):
self.x = x
def __call__(self):
return self.x
c = foo(4)
c.__sizeof__()
>>> 16
Which looks like the function version is a larger memory footprint.
I'd write the more complex functions and profile them.
If you want performance and only want access to values, then it would be best to use a built-in data type such as a tuple for best performance
精彩评论