优化Google Apps Script执行速度:2.9万行表格去重脚本耗时过长求助
代码慢的核心原因
你原代码的性能损耗完全来自高频调用Spreadsheet的读写接口:
- 每处理一行Masterlist数据,就要执行2次读取、1次写入、1次删除操作
- 每次判断重复时都遍历Seed表所有行逐行读取,时间复杂度是O(n²)
29000行数据下累计接口调用次数超过百万级,自然需要几十天才能跑完。
优化后代码
function getSheet(name) { return SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name); } function main() { // 一次性读取所有源数据到内存 const sourceSheet = getSheet('Masterlist'); const sourceData = sourceSheet.getDataRange().getValues(); // 跳过表头行 const dataRows = sourceData.slice(1); const seedRows = []; const duplicateRows = []; // 用Set存储已出现的所有邮箱,查找复杂度O(1) const existedEmails = new Set(); // 邮箱是第8列,索引为7 const EMAIL_COL_INDEX = 7; // 所有判断逻辑完全在内存中执行 for (const row of dataRows) { const emailCell = row[EMAIL_COL_INDEX]; // 邮箱为空直接判定为非重复 if (!emailCell) { seedRows.push(row); continue; } const currentEmails = emailCell.split("; "); let isDuplicate = false; // 检查当前行是否有邮箱已经存在 for (const email of currentEmails) { if (existedEmails.has(email)) { isDuplicate = true; break; } } if (isDuplicate) { duplicateRows.push(row); } else { seedRows.push(row); // 把当前行的所有邮箱加入已存在集合 currentEmails.forEach(email => existedEmails.add(email)); } } const targetSheet = getSheet('Seed'); const duplicateSheet = getSheet('Duplicates'); // 批量写入Seed表 if (seedRows.length > 0) { // 如果Seed表原来有数据需要覆盖可以取消注释下一行 // targetSheet.clearContents(); targetSheet.getRange(targetSheet.getLastRow() + 1, 1, seedRows.length, seedRows[0].length).setValues(seedRows); } // 批量写入Duplicates表 if (duplicateRows.length > 0) { // 如果Duplicates表原来有数据需要覆盖可以取消注释下一行 // duplicateSheet.clearContents(); duplicateSheet.getRange(duplicateSheet.getLastRow() + 1, 1, duplicateRows.length, duplicateRows[0].length).setValues(duplicateRows); } // 清空Masterlist除了表头的所有内容 if (dataRows.length > 0) { sourceSheet.deleteRows(2, dataRows.length); } }
优化点说明
- 全内存运算:所有读写操作只执行3次(读Masterlist、写Seed、写Duplicates),完全避免了单行操作的性能损耗
- 哈希查找优化:用Set存储已出现的邮箱,重复判断的时间复杂度从O(n)降到O(1),整体时间复杂度从O(n²)降到O(n)
- 批量操作:用
setValues一次性写入所有数据,比appendRow快数百倍
注意事项
- 运行前先备份整个表格数据,避免误操作丢失内容
- 29000行数据优化后预计运行时间不会超过1分钟
内容的提问来源于stack exchange,提问作者bella lugosi
相关产品推荐
相关产品推荐

