Apps Script考勤统计脚本运行缓慢,寻求性能优化方案
考勤追踪工具出勤统计性能优化问题
背景
我正在为工作开发考勤追踪工具,需要实现统计每位员工总出勤天数的功能。很久没写代码了,当前实现比较粗糙。
数据结构说明
(1代表出勤,0代表缺勤)
| 周末日期 | 日期 | Person1 | Person2 | Person 3 | etc. |
|---|---|---|---|---|---|
| 9/29/23 | Monday | 1 | 1 | 0 | ... |
| Tuesday | 1 | 0 | 0 | ... | |
| Wednesday | 0 | 1 | 1 | ... | |
| Thursday | 1 | 1 | 1 | ... | |
| Friday | 0 | 1 | 0 | ... | |
| Notes | Sick | ... | |||
| 10/6/23 | Monday | 1 | 1 | 1 | ... |
| Tuesday | 1 | 1 | 1 | ... | |
| Wednesday | 0 | 1 | 1 | ... | |
| Thursday | 1 | 0 | 1 | ... | |
| Friday | 0 | 1 | 0 | ... | |
| Notes | ... |
原本无Notes行时可直接对列求和,添加该行后需避免NaN错误。
现有代码
for (i = 0; i < roster.length; i++) { totals1.push(archive.getRange(1, 3+i).getValue()); // totals[0] contains names var sum = 0; var x = 1; while (archive.getRange(1+x, 2).getDisplayValue() != "") { if (archive.getRange(2+x, 3+i).getDisplayValue().length == 1) { // comment strings will have longer sum += +archive.getRange(2+x, 3+i).getDisplayValue(); // lengths than 1 so they won't be included } x++; } totals2.push(sum); // totals[1] contains sum } totals.push(totals1, totals2); var totals2d = [] for (i = 0; i < roster.length; i++) { totals2d[i] = [totals[0][i], totals[1][i]]; //combine both arrays to make 2d array }
问题
代码可正常运行,但处理60名员工需耗时约4分钟,且团队规模将扩大,运行时间会进一步增加。代码中其他嵌套循环部分仅需数秒即可完成,实在搞不懂这段代码为何速度如此缓慢,恳请帮忙优化性能!
内容的提问来源于stack exchange,提问作者B.A. Ceradsky
相关产品推荐
相关产品推荐

