如果我们看一下PEP 207 for Rich Comparisions,最后会看到这个有趣的句子:
已经存在的处理整数比较的内联仍然适用,在最常见的情况下不会产生性能成本。
所以似乎在 2.x 中对整数比较进行了优化。如果我们看一下源代码,我们会发现:
case COMPARE_OP:
w = POP();
v = TOP();
if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) {
/* INLINE: cmp(int, int) */
register long a, b;
register int res;
a = PyInt_AS_LONG(v);
b = PyInt_AS_LONG(w);
switch (oparg) {
case PyCmp_LT: res = a < b; break;
case PyCmp_LE: res = a <= b; break;
case PyCmp_EQ: res = a == b; break;
case PyCmp_NE: res = a != b; break;
case PyCmp_GT: res = a > b; break;
case PyCmp_GE: res = a >= b; break;
case PyCmp_IS: res = v == w; break;
case PyCmp_IS_NOT: res = v != w; break;
default: goto slow_compare;
}
x = res ? Py_True : Py_False;
Py_INCREF(x);
}
else {
slow_compare:
x = cmp_outcome(oparg, v, w);
}
因此,似乎在 2.x 中存在一个现有的性能优化——通过允许 C 代码直接比较整数——如果已经实现了丰富的比较运算符,则不会保留这种优化。
现在在 Python 3__cmp__
中不再支持,因此必须有丰富的比较运算符。现在,据我所知,这不会导致性能下降。例如,比较:
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit("2 < 1")
0.06980299949645996
到:
Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit("2 < 1")
0.06682920455932617
因此,似乎存在类似的优化,但我的猜测是,当考虑向后兼容性时,将它们全部放在 2.x 分支中将是一个太大的变化。
在 2.x 中,如果您想要丰富的比较方法,您可以通过operator
模块获得它们:
>>> import operator
>>> operator.gt(2,1)
True