and
==`==
is judged by "whether it is the same value", while ʻis` is judged by "whether it is the same object".
For example, in the following example
>>> a = "hello"
>>> b = "hello"
Both objects have the same value, so when compared with ==
, it returns True
.
>>> a == b
True
However, ʻis is judged by "is it the same object?" In Python, when you create an object, it is given a unique number. ʻIs
is identified by its number.
You can check the number with ʻid () `.
>>> id(a)
2827074142256
>>> id(b)
2827074145520
>>> a is b
False
ʻIs instanceis a function that compares the classes of objects. If it inherits another class, it returns
True` even when compared to the parent class
>>> class customint(int):
... pass
...
>>> c = customint()
>>> type(c) == int
False
>>> type(c) is int
False
>>> isinstance(c, int)
True
Execute each function 10,000,000 times (10 million times) and measure the execution time Repeat this 10 times to calculate the average For reference, I also run a function that loops 10,000,000 times without doing anything
#!/usr/bin/env python3
# coding: utf-8
from time import time
intvar = 0
n = 10 ** 7
def gettime(name, num=10):
"""
Execute 10 times, measure the execution time, and calculate the average
"""
def func(fn):
def wrapper(*args, **kwargs):
strat_t = time()
for a in range(num):
fn(*args, **kwargs)
dur = (time() - strat_t) / 10
print(name, "\t:", dur)
return wrapper
return func
@gettime("simple\t")
def simple():
for x in range(n):
pass
@gettime("equal\t")
def equal():
for x in range(n):
res = type(intvar) == int
if type(intvar) == True:
pass
@gettime("is\t")
def iscompare():
for x in range(n):
res = type(intvar) is int
@gettime("isinstance")
def isinstancecompare():
for x in range(n):
res = isinstance(intvar, int)
if __name__ == '__main__':
simple()
equal()
iscompare()
isinstancecompare()
(Unit: seconds)
Execution environment | Windows 10 Intel Core i7-8550U @ 1.80GHz RAM:16GB |
Sakura's VPS(v3) 1G |
---|---|---|
Empty loop | 0.1508335590362549 | 0.37562224864959715 |
== |
0.8364578723907471 | 1.9130330801010131 |
is |
0.8253042459487915 | 1.799116063117981 |
isinstance |
0.5259079456329345 | 1.3679522275924683 |
Execution time is
==
> is
>>> isinstance
It became a feeling.
So
――I want to do type comparison considering inheritance ――I'm not sure about inheritance, but I just want to find speed
In case of ʻis instance`,
--I want to ignore inheritance and perform type comparison
In that case, use ʻis`.
I used the decorator for the first time, but it's really convenient
Recommended Posts