效能

PHP 用戶端程式庫可讓您只花少許設定,就能更輕鬆地與 Google Ads API 互動。不過,效能會主要取決於程式庫的使用方式和整合方式。

大部分的最佳做法適用於所有語言。本指南將逐一介紹 PHP 專屬的功能。

Protobuf 實作

gRPC 和 Google Ads API 會使用 Protobuf,處理要求和回應訊息。我們提供兩種實作方式,但以 C 編寫的實作成效較佳。

詳情請參閱 Protobuf 指南

PHP 解譯器的作業模式

PHP 是一種多功能的指令碼語言,且會根據使用情況而提供許多作業模式。PHP CGI (共用閘道介面) 具有明顯的優勢,因為可在執行作業之間共用資源。

PHP 版本

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

未使用的 Google Ads API 版本

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

您可以放心從用戶端程式庫中移除未使用的 Google Ads API 版本專屬套件。因為這有助於加快執行速度或減少記憶體用量,因此用戶端程式庫提供公用程式,以程式方式執行。

範例

假設您要實作的用戶端程式庫僅使用最新版 API:v17,而您想移除對未使用的 API 版本支援:v16v15

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

"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 v15 and v16 of the Google Ads API.
echo "# Removing support..."
composer run-script remove-google-ads-api-version-support -- 15 16

# 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

下列執行輸出範例表示檔案大小將減少 50M,而唯一支援的版本為 V17

# Supported Google Ads API versions:
V15
V16
V17
# Vendor folder size:
110M    ./vendor
# Removing support...
> Google\Ads\GoogleAds\Util\ApiVersionSupport::remove
Removing support for the version 15 of Google Ads API...
Done
Removing support for the version 16 of Google Ads API...
Done
# Supported Google Ads API versions:
V17
# Vendor folder size:
60M     ./vendor

開發與正式環境

PHP 是一種解譯語言,其在執行前會先編譯指令。這通常是理想的做法,因為在開發期間,來源經常會隨著執行時間而改變。然而,由於穩定性和效能成為了主要考量,因此在實際工作環境時的情況則相反。

快取

強烈建議您使用快取功能,因為這麼做可儲存預先編譯的指令碼指示,藉此提高效能並增加穩定性。

OPcache 是最常用的解決方案,預設會提供使用。

自動儲值

自動載入功能很常見,因為它會載入類別的相關預先編譯資訊,以提高效能並增加穩定性。

PHP 用戶端程式庫符合 PSR-4 的自動載入機制,並做為 composer.json 檔案的一部分提供定義。之後即可立即使用 Composer 的專屬選項,例如 --optimize-autoloader--classmap-authoritative

Logging

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

詳情請參閱 Logging 指南

偵錯與剖析

建議您停用偵錯工具和分析器工具,因為這類工具通常會產生一些執行時間的負擔。

預先載入

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

指令碼必須設計來利用這項功能,但 PHP 用戶端程式庫並非通用的方法,因為沒有通用的 OPcache 預先載入。此外,特定專案和執行作業在記憶體用量與效能提升之間需要取捨的方式也息息相關。