Created
July 9, 2015 16:00
-
-
Save thomas-mangin/f3ba31e1bad1a358be73 to your computer and use it in GitHub Desktop.
staticmethod vs classmethod
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
def nop_function (): | |
pass | |
def access_function (): | |
local = Test.scoped_value | |
class Test (object): | |
scoped_value = 1 | |
@staticmethod | |
def nop_class_static (): | |
pass | |
@classmethod | |
def nop_class_method (cls): | |
pass | |
def nop_class_function (self): | |
pass | |
# | |
@classmethod | |
def access_class_method (cls): | |
local = cls.scoped_value | |
def access_class_function (self): | |
local = self.scoped_value | |
def timer (function,loop=10000000): | |
start = time.time() | |
for _ in range(loop): | |
function() | |
end = time.time() | |
print 'function %s took %f' % (function.__name__,end-start) | |
test = Test() | |
# class creation time | |
timer(Test) | |
# class access time | |
timer(nop_function) | |
timer(Test.nop_class_static) | |
timer(Test.nop_class_method) | |
timer(test.nop_class_function) | |
timer(access_function) | |
timer(Test.access_class_method) | |
timer(test.access_class_function) | |
yes, you just count create class time once. but if there is a need to create class instance each time, then classmethod is better, yes?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On my laptop :
function Test took 1.425494
function nop_function took 1.023233
function nop_class_static took 1.247149
function nop_class_method took 1.016509
function nop_class_function took 0.986712
function access_function took 1.345729
function access_class_method took 1.424856
function access_class_function took 1.349516
function Test took 0.011039
function nop_function took 0.021784
function nop_class_static took 0.135814
function nop_class_method took 0.021882
function nop_class_function took 0.130540
function access_function took 0.112920
function access_class_method took 0.142469
function access_class_function took 0.146806