性能

借助 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)。

日志记录

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

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

调试和分析

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

预加载

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

必须设计脚本才能利用此功能,但 PHP 客户端库则不会,因为没有实现 OPcache 预加载的通用方法,并且内存用量和性能增益之间的权衡很大程度上取决于给定项目和执行。