性能

PHP 客户端库可简化与 Google Ads API 的交互,只需您进行最少的配置。不过,性能在很大程度上取决于库的使用和集成方式。

这些最佳实践中的大多数都适用于 所有语言。本指南将介绍特定于 PHP 的最佳实践。

Protobuf 实现

ProtobufgRPC 和 Google Ads API 用于请求和响应消息。虽然有两种实现方式,但以 C 语言编写的实现方式具有更好的性能。

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

PHP 解释器的运行模式

PHP 是一种多功能的 脚本 语言,根据使用情况有多种 运行 模式。PHP CGI(通用网关接口)具有显著优势,因为它可以在执行之间共享资源。

PHP 版本

定期升级到较新的 PHP 版本是一种良好的做法,因为新版本通常具有更好的整体性能。支持的 PHP 版本列表。

未使用的 Google Ads API 版本

客户端库的所有版本都支持多个 Google Ads API 版本。 对于客户端库支持的每个 Google Ads API 版本,都有该版本的专用软件包。

可以安全地从客户端库中移除专用于未使用的 Google Ads API 版本的软件包。由于加快执行速度或减少内存占用可能很有用,因此客户端库提供了以编程方式执行此操作的实用程序。

示例

假设您要实现仅使用最新 API 版本 v25 的客户端库,并且想要移除对未使用 API 版本 v24v23 的支持。

在项目的 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 v23 and v24 of the Google Ads API.
echo "# Removing support..."
composer run-script remove-google-ads-api-version-support -- 23 24

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

# Supported Google Ads API versions:
V23
V24
V25
# Vendor folder size:
110M    ./vendor
# Removing support...
> Google\Ads\GoogleAds\Util\ApiVersionSupport::remove
Removing support for the version 23 of Google Ads API...
Done
Removing support for the version 24 of Google Ads API...
Done
# Supported Google Ads API versions:
V25
# Vendor folder size:
60M     ./vendor

开发与生产

PHP 是一种解释型语言 ,它会先编译指令,然后再执行指令。这通常是有利的,因为在开发期间,源代码经常会发生变化,而执行时间并不那么重要。不过,在生产期间,情况正好相反,因为稳定性和性能成为主要关注点。

缓存

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

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

自动充值

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

PHP 客户端库符合 PSR-4 自动加载标准,并在 composer.json 文件中提供定义。然后,您可以直接使用 Composer 的专用选项,例如 --optimize-autoloader--classmap-authoritative

日志记录

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

如需了解详情,请参阅日志记录指南

调试和分析

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

预加载

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

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