You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何简单比较操作拖慢了我的Python代码运行速度?

Vector2i类重载__eq__后代码变慢,替换直接比较仍无改善的原因及解决办法

我实现了一个Vector2i类,并重载了__eq__运算符:

class Vector2i:
    def __init__(self, x: int = 0, y: int = 0):
        self.x: int = x
        self.y: int = y

# (...)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

# (...)

原本运行正常,但代码突然大幅变慢。通过Python性能分析器排查,发现重载的运算符占用了大部分时间,疑似是性能瓶颈。

我尝试在代码的慢路径部分,将重载运算符替换为直接的Python比较:

# Inside a for loop.

    """
    if c.position != checkpos:
        continue
    """

    if c.position.x != checkpos.x or c.position.y != checkpos.y:
        continue

但结果完全相同,该比较操作仍导致代码大幅变慢。这是怎么回事?


解决方案
性能分析器的结果不够准确,真正的性能瓶颈并非比较操作本身,而是反复执行比较的循环。最终通过使用numpy处理大规模数组操作解决了该问题。

内容的提问来源于stack exchange,提问作者Guilherme Neves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:17:35