效能

PHP 用戶端程式庫可簡化與 Google Ads API 的互動,您只需進行最少的設定。不過,效能高度取決於程式庫的使用和整合方式。

這些最佳做法大多適用於所有語言。本指南將介紹 PHP 專屬的選項。

Protobuf 實作

gRPC 和 Google Ads API 會使用 Protobuf 處理要求和回應訊息。有兩種實作方式,但以 C 語言編寫的實作方式效能較佳。

詳情請參閱 Protobuf 指南

PHP 解譯器的作業模式

PHP 是一種多用途的指令碼語言,並具有多種作業模式,視使用情況而定。PHP CGI (Common Gateway Interface) 的顯著優勢在於,它可以在執行作業之間共用資源。

PHP 版本

建議定期升級至較新的 PHP 版本,因為新版本通常整體效能較佳。支援的 PHP 版本清單

未使用的 Google Ads API 版本

所有版本的用戶端程式庫都支援多個 Google Ads API 版本。 對於用戶端程式庫支援的每個 Google Ads API 版本,都有專屬的套件。

您可以從用戶端程式庫中安全地移除未使用的 Google Ads API 版本專用套件。這有助於加快執行速度或減少記憶體用量,因此用戶端程式庫提供實用工具,可透過程式輔助完成這項作業。

範例

假設您要實作僅使用最新 API 版本 v20 的用戶端程式庫,並想移除對未使用 API 版本 v19v18 的支援。

在專案的 composer.json 檔案中,定義利用用戶端程式庫提供的公用程式的 Composer 指令碼 (名為 remove-google-ads-api-version-support),位於 ApiVersionSupport 類別中:

"scripts": {
  "remove-google-ads-api-version-support": [
    "Google\\Ads\\GoogleAds\\Util\\ApiVersionSupport::remove"
  ]
}

接著,使用 Composer 指令碼,並以版本號碼做為參數,然後列印一些狀態訊息:

# Change the current directory to the project directory.
cd /path/to/the/project

# Install the project.
composer install

# Output the vendor folder size and the list of Google Ads API versions that are
# supported before removing support for Google Ads API versions.
echo "# Supported Google Ads API versions:"
find ./vendor/googleads/google-ads-php/src/Google/Ads/GoogleAds/V* -maxdepth 0 | grep -o '..$'
echo "# Vendor folder size:"
du -sh ./vendor

# Use the Composer script to remove the unused versions v18 and v19 of the Google Ads API.
echo "# Removing support..."
composer run-script remove-google-ads-api-version-support -- 18 19

# Output the vendor folder size and the list of Google Ads API versions that are
# supported after removing support for Google Ads API versions.
echo "# Supported Google Ads API versions:"
find ./vendor/googleads/google-ads-php/src/Google/Ads/GoogleAds/V* -maxdepth 0 | grep -o '..$'
echo "# Vendor folder size:"
du -sh ./vendor

以下執行輸出範例顯示檔案大小減少 50 MB,且唯一支援的版本是 V20

# Supported Google Ads API versions:
V18
V19
V20
# Vendor folder size:
110M    ./vendor
# Removing support...
> Google\Ads\GoogleAds\Util\ApiVersionSupport::remove
Removing support for the version 18 of Google Ads API...
Done
Removing support for the version 19 of Google Ads API...
Done
# Supported Google Ads API versions:
V20
# Vendor folder size:
60M     ./vendor

開發與正式環境

PHP 是解譯語言,會先編譯指令,再執行指令。這通常很有利,因為在開發期間,來源經常變更,而執行時間並非那麼重要。不過,在實際運作時,穩定性和效能才是主要考量,因此情況正好相反。

快取

快取是常見做法,而且強烈建議您使用,因為快取會儲存預先編譯的指令,藉此提升效能並提高穩定性。

OPcache 是最常用的解決方案,且預設為啟用。

自動儲值

自動載入很常見,因為載入類別的預先編譯資訊可提升效能並提高穩定性。

PHP 用戶端程式庫符合 PSR-4 自動載入標準,並在 composer.json 檔案中提供定義。Composer 的專用選項 (例如 --optimize-autoloader--classmap-authoritative) 隨即就能使用。

記錄

將記錄器設為 ERROR 等高層級,有助於減少執行時間負擔和記憶體用量。

詳情請參閱記錄指南

偵錯與分析

建議停用偵錯工具和剖析器工具,因為這些工具通常會造成一些執行時間負擔。

預先載入

自 PHP 7.4 起,OPcache 預先載入功能可用於預先載入記憶體中的指令碼,比一般快取更進一步。

必須設計指令碼才能善用這項功能,但 PHP 用戶端程式庫無法做到,因為沒有實作 OPcache 預先載入的通用方法,而且記憶體用量與效能提升之間的取捨,會因特定專案和執行作業而異。