一位开发者利用Claude和Cursor等AI代理进行了一项实验,测量代码重构对AI token消耗的影响[1]。该开发者构建的应用约包含15万行代码,其中Rust代码约12万行,并由AI代理全程编写[1]。
实验重点聚焦数据访问层的优化。研究者对初始规模为17155行的单一Rust文件进行了系统重构,共分13个步骤,严格遵循Martin Fowler《重构》第二版的定义[1]。重构完成后,后续AI处理该模块所需的输入token从159564降低至27360,实现了83%的降幅,累计节省132204个token[1]。按Claude Sonnet 5的定价标准(每百万token 3美元计算),单次代码变更可节省39.7美分[1]。
这一成果的关键在于AI代理无需加载整个代码库,只需识别执行特定任务的最小必要文件子集[1]。开发者指出:"这种节省是因为代理需要阅读更少的代码。但不是因为代码本身减少了。数据访问层的总代码量保持相当。因此为了实现这种节省,代理必须能够成功识别最小的必要文件子集。"[1] 不过,实验也暴露了AI的局限性——Claude在自主识别和应用重构机会方面表现欠佳,需要人工主动引导[1]。本次实验耗时约8小时,上限token消耗约500万[1]。
A software developer built a 150,000-line application entirely using AI agents such as Claude and Cursor, then conducted an experiment to quantify how code refactoring affects AI token consumption during subsequent development work [1]. The application is written primarily in Rust—approximately 120,000 lines—supplemented by TypeScript and Terraform [1].
The developer systematically refactored a single 17,155-line Rust data access layer file across 13 steps, following the strict definitions outlined in Martin Fowler's "Refactoring," Second Edition [1]. The refactoring yielded significant token savings: input tokens dropped from 159,564 to 27,360, representing a reduction of 132,204 tokens or 83% [1]. Using Claude Sonnet 5 pricing of $3 per million tokens, each code change would save approximately $0.397 in token costs [1]. The entire experiment required approximately 8 hours and consumed up to 5 million tokens in total [1].
The developer noted that the savings mechanism differs from simple code reduction: "This savings is because the agent needs to read less code. But not because the code itself became smaller. The total code volume in the data access layer remained substantially the same. Therefore, to achieve this savings, the agent must be able to successfully identify the minimal necessary subset of files" [1]. The experiment also revealed that Claude demonstrated limited effectiveness in autonomously identifying and applying refactorings, requiring manual guidance throughout the process [1].