| 中文说明 | English Explanation |
|---|---|
| Salesforce 是多租户平台,为保证资源公平,每个事务(Transaction)都有严格的系统限制,称为 Governor Limits。 | Salesforce runs on a multi-tenant architecture. To ensure fair resource usage, every transaction is limited by a set of system-enforced Governor Limits. |
这些限制包括:
English:
“Governor Limits control how much code can consume per transaction in Salesforce.
For example, 100 SOQL queries and 150 DML statements per synchronous transaction.
To avoid hitting limits, I follow three best practices:
- First, I bulkify my logic — never run queries or DML inside loops.
- Second, I use Maps and Sets for lookups and efficient filtering.
- Third, for large data processing, I move logic to asynchronous contexts like Batch or Queueable Apex.
If I hit heap or CPU time limits, I optimize by cleaning up memory, using SOQL FOR LOOP, and offloading computation into the database with aggregate functions.”
中文:
“Governor Limits 是 Salesforce 控制事务资源使用的核心机制。
比如同步事务最多 100 次 SOQL、150 次 DML。
我会遵循三条优化原则:
1️⃣ 批量化设计(避免循环中 SOQL/DML);
2️⃣ 用 Map/Set 提升查询效率;
3️⃣ 大数据任务用异步方式处理(Batch、Queueable)。
如果出现 Heap 或 CPU 限制,我会释放内存、用 SOQL FOR LOOP 流式处理,
并将计算逻辑尽量放入数据库完成。”
| 限制项 / Limitation | 说明 / Description | 同步限制 / Synchronous Limit | 异步限制 / Asynchronous Limit | 常见问题场景 & 优化方案 / Scenarios & Solutions |
|---|---|---|---|---|
| SOQL 查询次数 | 每个事务可执行的 SOQL 数量 | 100 | 200 | 🔸 循环中执行查询 → 合并查询或放出循环外🔸 使用 Map 缓存查询结果 |
| SOQL 返回记录数 | 每个事务最多返回的记录行 | 50,000 | 50,000 | 🔸 使用 WHERE 限定范围🔸 大数据使用 Batch Apex |
| DML 语句次数 | 每个事务中允许执行的 DML 操作 | 150 | 150 | 🔸 避免循环中 DML🔸 使用List批量DML操作 |
| DML 操作记录数 | 所有 DML 总处理记录行数 | 10,000 | 10,000 | 🔸 超限可改用 Batch 或 Queueable |
| Callout 调用次数 | HTTP/外部服务请求次数 | 100 | 100 | 🔸 合并外部调用🔸 使用异步 Future 处理 |
| Callout 超时时间 | 所有 Callout 累积超时时间 | 120s | 120s | 🔸 优化外部 API 响应时间 |
| Heap Size | 内存堆空间上限 | 6 MB | 12 MB | 🔸 清空不用的 List / Map🔸 使用 SOQL FOR LOOP 逐行处理 |
| CPU Time | Apex 逻辑运算时间 | 10,000ms | 60,000ms | 🔸 使用 Map 减少循环嵌套🔸 逻辑复杂任务放异步执行 |
| 查询返回 QueryLocator | Database.getQueryLocator() 结果集 |
10,000 | 10,000 | 🔸 用 Batch Apex 处理大量数据 |
| Batch 可查询记录 | start() 返回最大数据量 |
- | 50,000,000 | 🔸 避免复杂子查询导致超时 |
| Future 方法数 | 每事务可调用的 Future 方法 | 50 | Queueable 中最多 50 | 🔸 需要多步异步 → 改用 Queueable 链式任务 |
| System.enqueueJob() | 每事务可添加的 Queueable 作业数 | 50 | 1 | 🔸 控制异步提交频率 |
| 发送邮件数 | 每事务可发送的邮件数量 | 10 | 10 | 🔸 合并收件人或使用单封邮件通知 |
| 最大事务执行时间 | 总执行时长上限 | 10 分钟 | 10 分钟 | 🔸 分批执行任务,避免长事务 |
原因: 内存中存放大量数据(如嵌套 Map、长字符串、未释放变量)。
限制: 同步 6 MB、异步 12 MB。
优化策略:
✅ 避免: