我希望有人能解释为什么搜索对象引用列表比搜索普通列表慢得多。这是使用python“in”关键字来搜索我认为以“C编译器”速度运行的。我认为列表只是一个对象引用(指针)数组,因此搜索应该非常快。这两个列表在内存中正好是 412236 字节。
普通列表(搜索需要 0.000 秒):
alist = ['a' for x in range(100000)]
if 'b' in alist:
print("Found")
Run Code Online (Sandbox Code Playgroud)
对象引用列表(需要 0.469 !! 秒来搜索):
class Spam:
pass
spamlist = [Spam() for x in range(100000)]
if Spam() in spamlist:
print("Found")
Run Code Online (Sandbox Code Playgroud)
[obj for obj in spamlist if obj is target]
Run Code Online (Sandbox Code Playgroud)
3.其他一些更Pythonic的方式?