Skip to content

Instantly share code, notes, and snippets.

@thomas-mangin
Created July 9, 2015 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomas-mangin/f3ba31e1bad1a358be73 to your computer and use it in GitHub Desktop.
Save thomas-mangin/f3ba31e1bad1a358be73 to your computer and use it in GitHub Desktop.
staticmethod vs classmethod
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)
print
timer(Test.nop_class_static)
timer(Test.nop_class_method)
timer(test.nop_class_function)
print
timer(access_function)
timer(Test.access_class_method)
timer(test.access_class_function)
print
@thomas-mangin
Copy link
Author

On my laptop :

python test.py

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

pypy test.py

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

@xiaopeng163
Copy link

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