性能

您只需进行极少量配置,便可利用 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 版本的客户端库 (v16),并且您想要取消对未使用的 API 版本(v15v14)的支持。

在项目的 composer.json 文件中,在 ApiVersionSupport 类中定义一个名为 remove-google-ads-api-version-support 的 Composer 脚本,该脚本会利用客户端库提供的实用程序:

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

# 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,唯一剩余的受支持版本是 V16

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

开发与生产

PHP 是一种解释型语言,因为它会先编译指令,然后再执行指令。这通常很有用,因为在开发期间,源代码经常会发生变化,而执行时间则没那么重要。不过,在生产环境中则相反,因为稳定性和性能成为主要问题。

缓存

缓存很常见且强烈建议进行缓存,因为它可以通过存储预编译的脚本指令来提高性能并提高稳定性。

OPcache 是最常用的解决方案,并且默认可用。

自动充值

自动加载很常见,因为它可以通过加载有关类的预编译信息来提高性能并提高稳定性。

PHP 客户端库符合 PSR-4 的自动加载要求,并在 composer.json 文件中提供相应定义。然后,开箱即可使用 Composer 的专用选项(例如 --optimize-autoloader--classmap-authoritative)。

日志记录

将日志记录器设置为高级别(如 ERROR)有助于减少执行时间开销和内存消耗。

如需了解详情,请参阅 Logging 指南

调试和分析

我们建议您停用调试程序和性能分析器工具,因为它们通常会产生一些执行时间开销。

预加载

从 PHP 7.4 开始,OPcache 预加载可用于在内存中预加载脚本,比常规缓存更进一步。

必须设计脚本才能利用此功能,但 PHP 客户端库无法利用此功能,因为没有实现 OPcache 预加载的通用方法,并且内存用量与性能增益之间的权衡非常特定于给定项目和执行。