在指令碼中使用 JavaScript 作業,比呼叫其他服務快得多。在 Google Apps Script 本身完成任何工作,都比發出需要從 Google 伺服器或外部伺服器擷取資料的呼叫快得多,例如對 Google 試算表、Google 文件、Google 協作平台、Google 翻譯、UrlFetch 等發出的要求。如果能盡量減少指令碼對這些服務的呼叫次數,指令碼的執行速度就會更快。
[[["容易理解","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"]],["上次更新時間:2025-08-04 (世界標準時間)。"],[[["\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,["This document lists best practices that will help you improve the performance\nof your scripts.\n\nMinimize calls to other services\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\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\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[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\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."]]