在脚本中使用 JavaScript 操作比调用其他服务快得多。在 Google Apps 脚本本身中可以完成的任何操作都比需要从 Google 服务器或外部服务器(例如 Google 表格、Google 文档、Google 协作平台、Google 翻译、UrlFetch 等)提取数据的调用快得多。如果您能找到方法来最大限度地减少脚本对这些服务的调用,脚本的运行速度就会更快。
库是一种重用代码的便捷方式,但会略微增加启动脚本所需的时间。对于运行时间相对较长的脚本(例如用于清理 Google 云端硬盘文件的实用脚本),这种延迟并不明显,但对于反复进行短时间运行的 google.script.run 调用的客户端 HTML 服务界面,这种延迟会影响每次调用。由于存在此问题,因此应谨慎使用插件中的库,并且您可能需要在进行大量 google.script.run 调用的非插件脚本中避免使用库。
使用 Cache 服务
您可以使用缓存服务在脚本执行之间缓存资源。通过缓存数据,您可以减少获取数据的次数或频率。假设您在 example.com 上有一个 RSS Feed,需要 20 秒才能提取,并且您希望加快平均请求的访问速度。以下示例展示了如何使用 Cache Service 来加快对这些数据的访问速度。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003ePrioritize using JavaScript operations within your script to minimize slower calls to external services like Google Sheets or Docs.\u003c/p\u003e\n"],["\u003cp\u003eFor collaborative projects, leverage shared drives to streamline development and maintenance as files are owned by the group, not individuals.\u003c/p\u003e\n"],["\u003cp\u003eOptimize data processing by reading data into arrays, performing calculations, and writing results back in batches to minimize read/write operations.\u003c/p\u003e\n"],["\u003cp\u003eIn UI-heavy scripts or add-ons, use libraries sparingly as they can introduce delays in script execution, impacting user experience.\u003c/p\u003e\n"],["\u003cp\u003eUtilize the Cache service to store frequently accessed data, reducing the need for repeated fetching and improving script performance.\u003c/p\u003e\n"]]],[],null,["# Best Practices\n\nThis document lists best practices that will help you improve the performance\nof your scripts.\n\nMinimize calls to other services\n--------------------------------\n\nUsing JavaScript operations within your script is considerably faster than\ncalling other services. Anything you can accomplish within Google Apps Script\nitself will be much faster than making calls that need to fetch data from\nGoogle's servers or an external server, such as requests to Sheets, Docs,\nSites, Translate, UrlFetch, and so on. Your scripts will run faster if you can\nfind ways to minimize the calls the scripts make to those services.\n\nConsider collaborating with shared drives\n-----------------------------------------\n\nIf you are working on a script project with other developers, you can\n[collaborate on Apps Script projects with shared drives](/apps-script/guides/collaborating#collaborating_with_shared_drives).\nFiles in a shared drive are owned by the group, rather than individuals. This\nmakes development and maintenance of the project easier.\n\nUse batch operations\n--------------------\n\nScripts commonly need to read in data from a spreadsheet, perform calculations,\nand then write out the results of the data to a spreadsheet. Google Apps\nScript already has some built-in optimization, such as using look-ahead caching\nto retrieve what a script is likely to get and write caching to save what is\nlikely to be set.\n\nYou can write scripts to take maximum advantage of the built-in caching, by\nminimizing the number of reads and writes. Alternating read and write commands\nis slow. To speed up a script, read all data into an array with one command,\nperform any operations on the data in the array, and write the data out with\none command.\n\nHere's an example --- an example you should not follow or use. A script\nuses the following code to set the background colors of every cell in a\n100 x 100 spreadsheet grid. It uses as function named\n`getColorFromCoordinates()` (not shown here) to determine what color to use\nfor each cell: \n\n // DO NOT USE THIS CODE. It is an example of SLOW, INEFFICIENT code.\n // FOR DEMONSTRATION ONLY\n var cell = sheet.getRange('a1');\n for (var y = 0; y \u003c 100; y++) {\n xcoord = xmin;\n for (var x = 0; x \u003c 100; x++) {\n var c = getColorFromCoordinates(xcoord, ycoord);\n cell.offset(y, x).setBackgroundColor(c);\n xcoord += xincrement;\n }\n ycoord -= yincrement;\n SpreadsheetApp.flush();\n }\n\nThe script is inefficient: it loops through 100 rows and 100 columns, writing\nconsecutively to 10,000 cells. The Google Apps Script write-back cache helps,\nbecause it forces a write-back using flush at the end of every line. Because\nof the caching, there are only 100 calls to the Spreadsheet.\n\nBut the code can be made much more efficient by batching the calls. Here's a\nrewrite in which the cell range is read into an array called colors, the color\nassignment operation is performed on the data in the array, and the values in\nthe array are written out to the spreadsheet: \n\n // OKAY TO USE THIS EXAMPLE or code based on it.\n var cell = sheet.getRange('a1');\n var colors = new Array(100);\n for (var y = 0; y \u003c 100; y++) {\n xcoord = xmin;\n colors[y] = new Array(100);\n for (var x = 0; x \u003c 100; x++) {\n colors[y][x] = getColorFromCoordinates(xcoord, ycoord);\n xcoord += xincrement;\n }\n ycoord -= yincrement;\n }\n sheet.getRange(1, 1, 100, 100).setBackgrounds(colors);\n\nThe inefficient code takes about 70 seconds to run. The efficient code runs in\njust 1 second!\n\nAvoid libraries in UI-heavy scripts\n-----------------------------------\n\n[Libraries](/apps-script/guides/libraries) are a convenient way to reuse code,\nbut they slightly increase the time it takes to start the script. This delay\nisn't noticeable for relatively long-running scripts (like a utility script to\nclean up your Google Drive files), but for client-side\n[HTML Service](/apps-script/guides/html) user interfaces that make repeated,\nshort-running [`google.script.run`](/apps-script/guides/html/reference/run)\ncalls, the delay will affect every call. Because of this issue, libraries should\nbe used sparingly in [add-ons](/workspace/add-ons/overview), and you may want to\navoid them in non-add-on scripts that make lots of `google.script.run` calls.\n\nUse the Cache service\n---------------------\n\nYou can use the [Cache Service](https://developers.google.com/apps-script/class_cache)\nto cache resources between script executions. By caching data, you can reduce\nthe number of times or frequency with which you have to fetch the data.\nConsider the scenario where you have an RSS feed at example.com that takes 20\nseconds to fetch, and you want to speed up access on the average request. The\nexample below shows how to use the Cache Service to speed up access to this\ndata. \n\n function getRssFeed() {\n var cache = CacheService.getScriptCache();\n var cached = cache.get(\"rss-feed-contents\");\n if (cached != null) {\n return cached;\n }\n // This fetch takes 20 seconds:\n var result = UrlFetchApp.fetch(\"http://example.com/my-slow-rss-feed.xml\");\n var contents = result.getContentText();\n cache.put(\"rss-feed-contents\", contents, 1500); // cache for 25 minutes\n return contents;\n }\n\nNow, while you'll have to still wait 20 seconds if the item is not in cache,\nsubsequent accesses will be very fast until the item expires out of the cache\nin 25 minutes."]]