最佳做法
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
這份文件列出最佳做法,協助您提升指令碼的效能。
盡量減少對其他服務的呼叫
在指令碼中使用 JavaScript 作業,比呼叫其他服務快得多。在 Google Apps Script 本身完成任何工作,都會比發出需要從 Google 伺服器或外部伺服器擷取資料的呼叫快得多,例如對 Google 試算表、Google 文件、Google 協作平台、Google 翻譯、UrlFetch 等發出的要求。如果能盡量減少指令碼對這些服務的呼叫次數,指令碼的執行速度就會更快。
考慮使用共用雲端硬碟協作
如果您與其他開發人員共同處理指令碼專案,可以透過共用雲端硬碟協作處理 Apps Script 專案。共用雲端硬碟中的檔案是由群組 (而非個人) 所有。這有助於簡化專案的開發和維護作業。
使用批次作業
指令碼通常需要從試算表讀取資料、執行計算,然後將資料結果寫入試算表。Google Apps Script 已經內建一些最佳化功能,例如使用預先快取來擷取指令碼可能取得的內容,以及寫入快取來儲存可能設定的內容。
您可以編寫指令碼,盡量減少讀取和寫入次數,充分運用內建快取功能。交替讀取和寫入指令的速度緩慢。如要加快指令碼速度,請使用一個指令將所有資料讀取至陣列,對陣列中的資料執行任何作業,然後使用一個指令寫出資料。
以下是範例,但請勿照做或使用。指令碼會使用下列程式碼,為 100 x 100 的試算表格線中每個儲存格設定背景顏色。這個函式會使用名為 getColorFromCoordinates()
的函式 (此處未顯示),判斷每個儲存格要使用的顏色:
// DO NOT USE THIS CODE. It is an example of SLOW, INEFFICIENT code.
// FOR DEMONSTRATION ONLY
var cell = sheet.getRange('a1');
for (var y = 0; y < 100; y++) {
xcoord = xmin;
for (var x = 0; x < 100; x++) {
var c = getColorFromCoordinates(xcoord, ycoord);
cell.offset(y, x).setBackgroundColor(c);
xcoord += xincrement;
}
ycoord -= yincrement;
SpreadsheetApp.flush();
}
這個指令碼效率不彰,因為它會逐一處理 100 列和 100 欄,並連續寫入 10,000 個儲存格。Google Apps Script 回寫快取有助於解決這個問題,因為它會在每行結尾強制使用排清作業進行回寫。由於有快取,因此只會對試算表進行 100 次呼叫。
但只要批次處理呼叫,程式碼效率就能大幅提升。以下是重寫的程式碼,其中儲存格範圍會讀取至名為「colors」的陣列,顏色指派作業會在陣列中的資料上執行,而陣列中的值會寫入試算表:
// OKAY TO USE THIS EXAMPLE or code based on it.
var cell = sheet.getRange('a1');
var colors = new Array(100);
for (var y = 0; y < 100; y++) {
xcoord = xmin;
colors[y] = new Array(100);
for (var x = 0; x < 100; x++) {
colors[y][x] = getColorFromCoordinates(xcoord, ycoord);
xcoord += xincrement;
}
ycoord -= yincrement;
}
sheet.getRange(1, 1, 100, 100).setBackgrounds(colors);
效率不彰的程式碼執行時間約為 70 秒。有效率的程式碼只需 1 秒即可執行完畢!
避免在 UI 密集型指令碼中使用程式庫
程式庫是重複使用程式碼的便利方式,但會稍微增加啟動指令碼所需的時間。如果指令碼執行時間較長 (例如用於清除 Google 雲端硬碟檔案的公用程式指令碼),這項延遲不會造成明顯影響,但如果是透過HTML 服務建立的用戶端使用者介面,且會重複進行執行時間較短的 google.script.run
呼叫,每次呼叫都會受到延遲影響。因此,在外掛程式中應盡量少用程式庫,如果非外掛程式指令碼會進行大量 google.script.run
呼叫,建議避免使用程式庫。
使用快取服務
您可以使用 Cache Service 在指令碼執行期間快取資源。快取資料可減少擷取資料的次數或頻率。假設 example.com 有一個 RSS 饋給,擷取時間為 20 秒,而您想加快平均要求的存取速度。下例說明如何使用 Cache 服務加快存取這項資料的速度。
function getRssFeed() {
var cache = CacheService.getScriptCache();
var cached = cache.get("rss-feed-contents");
if (cached != null) {
return cached;
}
// This fetch takes 20 seconds:
var result = UrlFetchApp.fetch("http://example.com/my-slow-rss-feed.xml");
var contents = result.getContentText();
cache.put("rss-feed-contents", contents, 1500); // cache for 25 minutes
return contents;
}
現在,如果項目不在快取中,您仍須等待 20 秒,但後續存取速度會非常快,直到項目在 25 分鐘後從快取中過期為止。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-31 (世界標準時間)。
[null,null,["上次更新時間: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."]]