Courseiva

CCNA Performance Questions

55 questions · Performance · All types, answers revealed

1
MCQhard

An Apex trigger is failing due to a 'System.LimitException: Too many DML statements: 151'. What is the optimal refactoring approach?

A.Increase the DML statement limit in the Apex class.
B.Refactor the code to collect records in a List and perform one DML.
C.Move the logic to a @future method to allow more DML.
D.Use the Database.update() method with allOrNone set to false.
AnswerB

Bulkification is the core design pattern for Salesforce development. Moving DML outside the loop ensures that only one DML statement is used regardless of the number of records, which completely eliminates the 'Too many DML statements' error and makes the code scalable and highly performant.

Why this answer

The error clearly indicates the failure to bulkify DML. The solution is to collect all records needing updates into a single list and perform one DML statement after the loop. This reduces 150+ individual operations to one, keeping the code within governor limits and significantly improving performance by reducing the number of round-trips to the database during the transaction processing cycle.

Exam trap

Candidates often mistakenly attempt to fix the error by increasing the batch size or splitting the code into multiple triggers, rather than addressing the core lack of bulkification.

2
MCQmedium

A developer is reviewing a custom Lightning Web Component that displays a list of 10,000 Contacts. The component uses a wire adapter to call an Apex method that returns all Contacts in a single response. Users report that the component loads very slowly and sometimes freezes. What is the most effective way to improve the component's performance?

A.Use `@wire` with `getRecord` instead of a custom Apex method to leverage Lightning Data Service caching.
B.Implement pagination or infinite scrolling to load Contacts in smaller chunks.
C.Move the data retrieval to a `setTimeout` function to defer loading until after the component renders.
D.Increase the Apex heap size by using `@AuraEnabled(cacheable=true)` to allow larger responses.
AnswerB

Loading 10,000 records at once overwhelms the browser and the network, causing slow rendering and freezes. Pagination or infinite scrolling limits the number of records loaded and displayed at a time, reducing memory usage and improving responsiveness. This is a standard performance optimization for large data sets in Lightning Web Components.

Why this answer

Rendering 10,000 records at once is inefficient and can cause browser freezes. Implementing pagination or infinite scrolling loads data in smaller batches, reducing initial load time and memory consumption. This approach is recommended for large data sets in Lightning Web Components.

Other options either misapply features or do not address the volume of data.

Exam trap

The trap here is thinking that caching or deferring the load can solve performance issues caused by large data volume, when the real solution is to reduce the amount of data loaded at once.

3
MCQmedium

A developer is building an Apex batch class that processes 2 million Account records. The start method uses the following SOQL query: [SELECT Id, Name FROM Account WHERE BillingCountry = 'US']. The query is selective because BillingCountry is indexed. However, during testing, the batch job fails with a 'First error: Apex CPU time limit exceeded' error. The developer suspects that the issue is related to the query performance. Which of the following is the most likely cause of the CPU timeout?

A.The query is returning too many fields, causing excessive heap size and indirectly CPU timeout.
B.The execute method contains inefficient code, such as nested loops or excessive DML operations, causing high CPU usage per record.
C.The query is not selective enough, causing a full table scan.
D.The batch size is set to the default of 200, causing too many batches and excessive overhead.
AnswerB

The CPU timeout occurs during execution, not querying. Inefficient code in the execute method, such as nested loops, multiple DML statements per record, or complex calculations, can consume excessive CPU time. With 2 million records, even small inefficiencies are amplified. Optimizing the execute method is the correct fix.

Why this answer

The CPU timeout is caused by inefficient processing in the execute method, not the query. The query is selective and returns only necessary fields. With millions of records, nested loops, multiple DML calls, or complex calculations can exceed the CPU limit.

The developer should optimize the execute method by reducing operations per record, using collections efficiently, and minimizing DML.

Exam trap

The trap here is assuming that a selective query prevents CPU timeouts, when the real issue lies in the processing logic within the batch execute method.

4
MCQhard

A developer is working on a Lightning Web Component that displays a list of 10,000 custom object records. The component currently uses an Apex controller method that returns all records in a single call, causing slow load times and occasional heap size limit exceptions. Which approach should the developer take to improve performance?

A.Implement pagination in the Apex controller to return a limited number of records per call, and use the Lightning Web Component to request subsequent pages as needed.
B.Increase the heap size limit by using the @AuraEnabled annotation with the 'continuation' attribute to handle long-running requests.
C.Use the @AuraEnabled(cacheable=true) annotation on the Apex method to cache the results on the client side.
D.Move the data retrieval logic to a Visualforce page and embed it in the Lightning Web Component using an iframe.
AnswerA

Pagination reduces the amount of data transferred in a single call, lowering heap usage and improving load times. The LWC can request pages on demand, providing a better user experience. This approach avoids hitting heap size limits and is a standard pattern for handling large datasets in Lightning.

Why this answer

Pagination is the best approach because it breaks the large dataset into smaller, manageable chunks. This reduces the amount of data processed and transferred at once, avoiding heap size limit exceptions and improving page load times. The LWC can request additional pages as the user scrolls or navigates, providing a responsive experience.

Exam trap

The trap here is thinking that client-side caching or increasing heap size can solve the problem, but heap limits are fixed and caching does not reduce the initial payload size.

5
MCQmedium

A developer is building a high-performance REST API integration. Which of the following is the most important practice for ensuring the integration handles high throughput?

A.Use individual REST API calls for every record update.
B.Utilize the Composite API to batch multiple operations.
C.Disable all triggers during the integration process.
D.Increase the API timeout duration to five minutes.
AnswerB

The Composite API allows developers to combine multiple SObject operations into a single request. This drastically reduces the number of API calls needed to sync large datasets, minimizing the impact on API limits and reducing the network latency associated with multiple round-trips to the Salesforce server.

Why this answer

High throughput requires minimizing the cost per request. By using bulk-enabled API endpoints, such as the Bulk API or Composite resources, a developer can process multiple records in a single request. This reduces the overhead of authentication, network latency, and server-side processing, allowing the integration to scale efficiently and stay well within the organization's API request limits, which is vital for high-volume data synchronization scenarios.

Exam trap

Test-takers frequently choose standard single-record REST endpoints instead of batch-oriented resources when asked about high-throughput integrations.

6
MCQmedium

A developer is optimizing an Apex trigger that processes a large number of records. The trigger currently performs a SOQL query inside a loop to check for duplicate records. This causes a 'Too many SOQL queries: 101' error when more than 100 records are processed. What is the best way to refactor the trigger to avoid this error?

A.Use Database.query with a bind variable inside the loop to dynamically build the query.
B.Use a SOQL query with a LIMIT clause inside the loop to reduce the number of records returned.
C.Enable deferred sharing on the trigger to reduce the number of SOQL queries.
D.Move the SOQL query outside the loop and use a Map to store the results for lookup.
AnswerD

Moving the SOQL query outside the loop and storing results in a Map is a best practice for bulkification. It reduces the number of queries to one, regardless of the number of records processed. The Map allows efficient lookup of existing records by a key, such as a unique field, avoiding repeated database calls within the loop.

Why this answer

The correct approach is to bulkify the trigger by moving the SOQL query outside the loop and using a Map for efficient lookups. This reduces the number of queries to one, well within governor limits. It is a fundamental Apex best practice to avoid SOQL or DML operations inside loops, ensuring scalability and performance.

Exam trap

The trap here is thinking that limiting records per query or using dynamic SOQL changes the query count, when the governor limit tracks the number of query executions, not the size of results.

7
MCQmedium

A developer is optimizing a Visualforce page that displays a large table of OpportunityLineItem records. The page uses a standard controller with an extension that queries all related OpportunityLineItems for an Opportunity. The page loads slowly for Opportunities with thousands of line items. The developer wants to improve performance without changing the user interface significantly. Which approach is most effective?

A.Use JavaScript Remoting to load all records asynchronously after the page renders.
B.Set the readOnly attribute of the <apex:page> component to true.
C.Increase the view state limit by contacting Salesforce support to raise the limit.
D.Implement pagination using a StandardSetController to limit the number of records displayed per page.
AnswerD

StandardSetController supports pagination and reduces the number of records loaded and rendered at once. This decreases view state size and improves page load time. It is a standard approach for handling large data sets in Visualforce without major UI changes.

Why this answer

Pagination with StandardSetController limits the records loaded and rendered per page, reducing view state and improving load time. It is the most effective approach for large data sets in Visualforce without changing the UI significantly. Other options either do not reduce data volume or are not feasible.

Exam trap

The trap here is assuming that readOnly or asynchronous loading solves the performance issue, when the real problem is the volume of records rendered on the page.

8
MCQmedium

A developer is writing a SOQL query on a custom object with 5 million records. The query filters on a custom field that is not indexed and returns a large number of records. The query is running slowly and sometimes fails with a 'Non-selective query' error. What should the developer do to improve query performance?

A.Add a LIMIT clause to the query to reduce the number of records returned.
B.Use a FOR UPDATE clause to lock the records and improve query speed.
C.Use a SOQL query with a subquery to filter the records more efficiently.
D.Create a custom index on the custom field used in the WHERE clause.
AnswerD

Creating a custom index on the field used in the WHERE clause makes the query selective by allowing the database to quickly locate matching records. This reduces the number of records scanned and improves performance. Salesforce allows custom indexes on custom fields, which is a standard solution for non-selective queries on large objects.

Why this answer

The best solution is to create a custom index on the custom field used in the WHERE clause. This makes the query selective, allowing Salesforce to use the index to retrieve records efficiently and avoid the 'Non-selective query' error. Custom indexes are essential for optimizing queries on large custom objects.

Exam trap

The trap here is thinking that limiting results or adding subqueries can fix selectivity, when the real fix is indexing the filtered field to avoid full table scans.

9
MCQhard

A developer is optimizing a Visualforce page that displays a list of accounts with their related contacts. The page uses a standard controller with an extension and a repeater component. The developer notices that the page is slow when there are many accounts, each with several contacts. What is the most likely cause of the performance issue?

A.The page is not using JavaScript remoting for data retrieval.
B.The page is using a standard controller without a custom extension.
C.The extension is querying contacts for each account inside a loop, causing a query per account.
D.The page is using a repeater component instead of a data table.
AnswerC

Querying related records inside a loop results in multiple SOQL queries, leading to governor limit exceptions and slow performance. Each query adds overhead and can quickly exceed the 100 SOQL query limit. The correct approach is to use a single query with a relationship subquery or a separate query for all contacts and then map them to accounts in memory, avoiding the N+1 query problem.

Why this answer

The most likely cause is the N+1 query problem, where the extension queries contacts for each account individually. This results in many SOQL queries, slowing down the page and risking governor limits. The solution is to query all contacts in a single query and then associate them with accounts in memory, or use a relationship subquery.

This reduces the number of queries to one or two, improving performance.

Exam trap

The trap here is focusing on the Visualforce component type rather than the underlying query pattern that causes multiple database calls.

10
MCQhard

A developer is optimizing a Visualforce page that displays a large dataset using a StandardSetController. The page currently loads slowly because it queries all records at once. The developer wants to implement pagination to improve performance. Which approach should be used?

A.Use the @ReadOnly annotation on the controller to allow the page to query all records without hitting governor limits, then paginate client-side.
B.Use SOQL OFFSET to manually paginate the records in the controller, fetching only the records for the current page.
C.Use a custom controller with a SOQL query that uses LIMIT and OFFSET, and implement pagination logic manually.
D.Use the StandardSetController's setPageSize method to limit the number of records per page and rely on its built-in pagination.
AnswerD

The StandardSetController is designed for pagination. By setting the page size, the controller automatically handles fetching only the records needed for the current page, reducing the initial query load. This is the most efficient way to implement pagination with minimal custom code.

Why this answer

The StandardSetController is specifically designed to handle pagination efficiently. By setting the page size, it automatically limits the query to the records needed for the current page, reducing the initial load and memory footprint. Manual pagination with OFFSET or client-side pagination does not offer the same performance benefits and often introduces additional complexity or inefficiencies.

Exam trap

The trap here is assuming that using OFFSET or client-side pagination is equivalent to StandardSetController, when in fact StandardSetController is optimized for server-side pagination and avoids the performance pitfalls of large offsets.

11
MCQmedium

A developer is optimizing an Apex trigger on the Opportunity object that updates related OpportunityLineItem records. The trigger currently performs a SOQL query for each OpportunityLineItem to check a field on the parent Opportunity. This causes performance degradation and governor limit errors. Which technique should the developer use to improve performance?

A.Add a LIMIT clause to the SOQL query to reduce the number of records returned.
B.Move the SOQL query to a future method to run asynchronously.
C.Use a Map to store parent Opportunity records and reference them in the loop.
D.Use a trigger handler framework to separate logic from the trigger.
AnswerC

Using a Map to store parent Opportunity records allows the trigger to avoid querying inside a loop. The developer can query all necessary Opportunities once, populate a Map keyed by Id, and then retrieve parent records from the Map within the loop. This reduces the number of SOQL queries to one, improving performance and avoiding governor limits.

Why this answer

Using a Map to store parent Opportunity records is the correct approach because it bulkifies the code by querying all necessary Opportunities once and then referencing them in the loop. This eliminates the query inside the loop, reducing the number of SOQL queries and improving performance. The other options do not address the root cause.

Exam trap

The trap here is thinking that moving the query to a future method or adding a LIMIT solves the loop query problem, when the real fix is to bulkify by using a Map.

12
MCQmedium

Refer to the exhibit. A developer is reviewing a debug log for a failed transaction. What is the primary performance issue identified in the log snippet?

A.The transaction failed due to too many SOQL queries being executed.
B.The transaction failed because the heap size limit was exceeded during processing.
C.The transaction failed because the CPU time exceeded the 10,000 ms limit.
D.The transaction failed because the number of query rows exceeded 50,000.
AnswerC

The log explicitly states that the Maximum CPU time was 10,005 milliseconds, which is over the 10,000 ms synchronous limit. The '*CLOSE TO LIMIT*' or actual exceeding of the number causes a LimitException. This means the code spent too long executing logic, loops, or transformations, causing the platform to terminate the request.

Why this answer

The debug log shows the cumulative limit usage at the end of a transaction. The 'Maximum CPU time' entry indicates that 10,005 milliseconds were used, which exceeds the synchronous governor limit of 10,000 milliseconds. This results in a LimitException, and the transaction is rolled back, regardless of how many queries or rows were processed.

Exam trap

Candidates often mistake CPU limit errors for SOQL query limit errors, failing to distinguish between the 10,000 ms execution time limit and the 100 query limit.

13
MCQeasy

A developer is writing an Apex trigger that updates a related object's records when a parent record is updated. The trigger currently performs a SOQL query for each child record to check if an update is needed. What is the most efficient way to optimize this trigger?

A.Move the SOQL query into a helper method and call it from the trigger to improve code organization.
B.Set the trigger to run asynchronously using @future to avoid governor limits.
C.Use a single SOQL query to retrieve all related child records for the parent records in the trigger, then process them in a loop.
D.Use a Map to cache child records after the first query, and reuse the cached data for subsequent iterations.
AnswerC

Querying all related child records in one SOQL query outside of any loop is the bulkified approach. It avoids the N+1 query problem and stays within governor limits. The trigger can then iterate over the retrieved records to perform necessary updates, ensuring efficiency and scalability.

Why this answer

The trigger's performance issue is caused by executing a SOQL query for each child record, which is a classic N+1 query problem. The optimal solution is to perform a single SOQL query to retrieve all necessary child records for the parent records in the trigger context. This bulkified approach minimizes database calls, respects governor limits, and improves performance.

Exam trap

The trap here is thinking that caching or asynchronous processing can fix the performance problem, when the real fix is to eliminate the per-record query by bulkifying.

14
MCQhard

A developer needs to aggregate data from 10 million rows. Which approach is the most efficient for preventing governor limit issues?

A.Retrieve all records and aggregate them in an Apex loop.
B.Use SOQL with GROUP BY to perform aggregation in the database.
C.Process records in small batches using a flow.
D.Use a custom index on all fields involved in the query.
AnswerB

Using the GROUP BY clause allows the database engine to perform the aggregation, which is highly optimized. This approach avoids transferring large volumes of data to the Apex heap, effectively preventing memory and CPU limit errors while providing the results in a much faster, more efficient manner.

Why this answer

For massive datasets, standard aggregate queries may hit CPU or query time limits. Using the 'Group By' clause in SOQL is the most optimized method, as the aggregation is performed at the database level by the Salesforce query engine. This avoids pulling millions of records into Apex memory, keeping heap usage low and ensuring the transaction remains well within governor limits while delivering results rapidly.

Exam trap

Test-takers frequently attempt to pull millions of records into an Apex collection and perform custom loops for aggregation, hitting severe heap size and CPU limits.

15
MCQmedium

A developer is building an Apex trigger that processes 200 Opportunity records on insert. The trigger needs to query all related OpportunityLineItem records to calculate a total. To avoid hitting the SOQL query limit, which approach should the developer use?

A.Use a separate SOQL query for each Opportunity but limit the loop to 100 iterations to stay within limits.
B.Perform a SOQL query inside a loop that iterates over each Opportunity record to fetch its line items individually.
C.Leverage a map of OpportunityLineItem records populated by a prior query in the trigger's initial data retrieval.
D.Use a single SOQL query in the trigger to retrieve all OpportunityLineItem records for all Opportunity IDs in the trigger context.
AnswerD

A single SOQL query that uses a WHERE clause with an IN binding on the trigger's Opportunity IDs (e.g., 'WHERE OpportunityId IN :oppIds') retrieves all necessary child records in one call. This respects the governor limit of 100 SOQL queries per transaction and is the standard bulkification pattern.

Why this answer

The correct approach is to bulkify the trigger by performing one SOQL query that retrieves all related OpportunityLineItem records for all Opportunities in the trigger context. This avoids the governor limit on the number of SOQL queries and ensures the trigger scales for bulk operations. Querying inside a loop or per record is inefficient and will fail with large data volumes.

Exam trap

The trap here is assuming that querying inside a loop is acceptable if the number of records is small, but governor limits apply regardless of batch size and can be exceeded even with moderate data volumes.

16
MCQmedium

A developer is building an Apex batch job that processes 50,000 Account records. The batch class uses `Database.executeBatch` with a batch size of 200. After running the job, the developer notices that the job takes significantly longer than expected and sometimes fails with `UNABLE_TO_LOCK_ROW` errors on the Account object. What is the most likely cause of the performance degradation?

A.The batch job is running in parallel with another batch job that updates the same Account records, causing lock contention.
B.The batch job is using a SOQL query without a WHERE clause, causing a full table scan.
C.The batch size is too large, causing excessive locking on the Account records.
D.The batch job is not using `Database.Stateful`, causing it to lose state between batches.
AnswerA

When two batch jobs or processes attempt to update the same records concurrently, row-level locks are held, leading to `UNABLE_TO_LOCK_ROW` errors and longer runtimes. The default batch size of 200 is not inherently problematic. The scenario indicates concurrent access, which is the most plausible cause of the locking and slowdown.

Why this answer

The `UNABLE_TO_LOCK_ROW` error occurs when multiple processes attempt to modify the same records simultaneously. In this scenario, the batch job likely runs concurrently with another process updating the same Accounts, causing lock contention and slowing down the job. Adjusting batch size or query selectivity would not resolve the locking issue; coordinating the timing of updates is necessary.

Exam trap

The trap here is assuming that batch size is the primary cause of locking errors, when in fact concurrent updates from other processes are the usual culprit.

17
MCQmedium

A developer is writing an Apex trigger on the Case object that updates a custom field on the Account when a Case is closed. The trigger currently performs a SOQL query to retrieve the Account for each Case in Trigger.new. The developer wants to optimize the trigger to handle bulk updates of up to 200 Cases without hitting governor limits. What is the best practice to achieve this?

A.Use a SOQL query inside a for loop to retrieve each Account and update it immediately.
B.Use a Map to store the Accounts from Trigger.new, but query the Accounts in the trigger's constructor.
C.Use a single SOQL query to retrieve all related Accounts based on the AccountId values from Trigger.new, then use a Map to update the Accounts.
D.Use a Database.query call with a bind variable for each AccountId to retrieve the Accounts in a single query.
AnswerC

Collecting all AccountId values from Trigger.new and performing one SOQL query to retrieve the related Accounts is the best practice for bulkification. Using a Map to relate Accounts to Cases allows efficient updates without additional queries. This approach ensures the trigger can handle up to 200 records within governor limits, reducing the number of queries to one.

Why this answer

The best practice for bulkifying a trigger is to collect all necessary IDs and perform a single SOQL query to retrieve related records. Using a Map to correlate the records allows efficient updates without additional queries. This reduces the number of queries to one, well within governor limits, and ensures the trigger can handle bulk updates.

The other options either cause multiple queries or are not applicable to triggers.

Exam trap

The trap here is thinking that using Database.query with bind variables is necessary for bulkification, when a simple static SOQL query with an IN clause is sufficient and more straightforward.

18
MCQmedium

A developer maintains an Apex class that performs a callout to an external REST service and then writes the response into Salesforce records. The callout occasionally takes longer than expected, and the developer wants to ensure the transaction can recover gracefully without leaving partial data. Which approach best addresses this?

A.Use Database.setSavepoint() before the callout and Database.rollback() after the callout to undo the external request.
B.Move the callout into a future method and perform the DML in the original synchronous transaction.
C.Perform the callout before any DML and use a savepoint so that if the callout or subsequent DML fails, the transaction can roll back the DML.
D.Set a shorter HTTP timeout using the HttpRequest.setTimeout method and rely on the timeout to prevent partial writes.
AnswerC

Apex callouts cannot be rolled back, so the safest pattern is to make the callout first, then wrap the DML in a savepoint and roll back if the write fails. This prevents partial data from being committed when the external response is unusable. It also keeps the callout outside any open savepoint scope, which is required because a callout after uncommitted DML in the same transaction causes a System.CalloutException.

Why this answer

Because external callouts are not transactional with the database, the reliable pattern is callout first, then savepoint-protected DML with rollback on failure. This keeps the transaction consistent and respects the rule that a callout cannot follow uncommitted DML in the same Apex transaction.

Exam trap

The trap here is believing a savepoint can undo an external callout, when savepoints only roll back database changes within the current transaction.

19
Multi-Selecthard

Which THREE factors contribute to slow execution of SOQL queries in Salesforce?

Select 3 answers
A.Using indexed fields in the WHERE clause.
B.Querying on unindexed fields with high cardinality.
C.Using OR conditions that bypass existing indexes.
D.Selecting a small number of fields from the object.
E.Deeply nested relationship queries across many levels.
AnswersB, C, E

Unindexed fields force a full table scan. In objects with millions of records, this is extremely slow. When the field also has high cardinality, the query optimizer cannot easily narrow down the results, leading to significant delays as the engine parses every single record in the object table.

Why this answer

SOQL performance is influenced by data volume, indexing, and query complexity. Queries on unindexed fields, excessive record scanning, and sub-optimal joins all force the database to work harder, increasing CPU time and latency. Understanding these factors allows developers to write more efficient queries that leverage existing indexes and minimize the amount of data the system must process to return results.

Exam trap

Candidates often forget that OR conditions and leading wildcards in SOQL filters can invalidate existing indexes, forcing the database to perform a full table scan, killing performance.

20
MCQhard

A developer is building a Visualforce page that displays a custom object's related list with 5,000 child records. The controller currently performs a SOQL query inside a getter method that is called multiple times during page rendering, and users report the page takes over 30 seconds to load. The developer needs to improve performance without changing the page's functionality. Which approach should the developer take?

A.Set the page's readOnly attribute to true so that the query is executed in a read-only context and no longer counts against governor limits.
B.Move the SOQL query into the constructor and store the results in a private member variable, then have the getter return that cached collection.
C.Add a @future annotation to the getter method so the SOQL query executes asynchronously and does not block the page render.
D.Replace the SOQL query with a SOSL search to retrieve the child records more efficiently across multiple objects.
AnswerB

A getter is invoked repeatedly during Visualforce rendering, so placing the query inside it causes redundant database calls. Moving the query to the constructor executes it once per request and caches the result in a member variable. This reduces query count, avoids repeated database work, and directly addresses the slow page load while preserving the displayed related list.

Why this answer

Visualforce getters are invoked each time the expression is evaluated during rendering, so a query inside a getter runs repeatedly. Caching the query result in the controller constructor executes it only once per request. This reduces database round trips and CPU usage, improving page load time.

The other options either violate Apex rules, use the wrong query language, or do not eliminate repeated execution.

Exam trap

The trap here is assuming that setting readOnly or using asynchronous execution will automatically fix slow rendering, when the real issue is that a getter re-runs its query on every evaluation.

21
Multi-Selectmedium

A developer is optimizing an Apex class that performs a large number of DML operations. The class currently updates records one at a time in a loop. Which two techniques should be used to improve performance? (Choose two.)

Select 2 answers
A.Use Database.update with the allOrNone parameter set to false.
B.Use the insert method instead of update to avoid conflicts.
C.Use a Map to deduplicate records before performing DML.
D.Collect records into a list and perform a single DML operation outside the loop.
E.Use the @future annotation to perform DML asynchronously.
AnswersC, D

Deduplicating records with a Map ensures that each record is processed only once, reducing the number of DML operations and avoiding errors like duplicate updates. This is especially important when the same record might be updated multiple times in a loop. Combining deduplication with bulk DML further optimizes performance by minimizing the data processed.

Why this answer

The two key techniques are bulkifying DML by collecting records into a list and performing a single DML call, and using a Map to deduplicate records to avoid redundant operations. These reduce the number of DML statements and ensure efficient processing within governor limits. The other options do not address the core inefficiency of per-record DML.

Exam trap

The trap here is thinking that asynchronous processing or changing the DML type solves performance issues, when the real fix is reducing the number of DML statements.

22
MCQmedium

A developer is writing an Apex trigger on the Account object that performs a SOQL query inside a loop to retrieve related Contacts. To adhere to performance best practices and avoid governor limits, what is the most efficient pattern to implement?

A.Use the Database.getQueryLocator method within the loop to retrieve records.
B.Move the SOQL query into a static method that is called by the trigger.
C.Collect related IDs in a Set, query all Contacts once, and store them in a Map for lookup.
D.Increase the SOQL query limit by using the @ReadOnly annotation on the method.
AnswerC

Bulkifying the query by using a Set of IDs allows for a single SOQL statement. Storing the results in a Map provides O(1) time complexity for subsequent record lookups, which is significantly more efficient than nested loops or repeated database queries within the execution context.

Why this answer

Retrieving data inside a loop creates an N+1 query problem, which rapidly consumes SOQL limits and degrades performance. By collecting IDs into a Set and performing a single bulkified query before processing the records, the developer reduces the total number of round-trips to the database. This pattern is essential for maintaining application scalability and ensuring the trigger remains performant as the data volume grows within the production environment.

Exam trap

Candidates often use a map inside the loop or attempt to query without pre-collecting IDs, which still results in hitting the SOQL limit during bulk operations.

23
MCQmedium

A developer is building an Apex controller for a Visualforce page that must display a list of 2,000 Contacts for an Account. The current implementation uses a SOQL query inside a loop to fetch Contacts for each Account row, resulting in sluggish page loads and occasional governor limit errors. Which approach should the developer take to improve performance?

A.Move the SOQL query outside the loop and use a Map to correlate Contacts to Accounts.
B.Add a LIMIT clause to the SOQL query inside the loop to reduce the number of records returned per Account.
C.Use Database.getQueryLocator to handle the Contacts and bind the result to the page.
D.Replace the SOQL query with a SOSL search to retrieve all Contacts at once.
AnswerA

This approach eliminates redundant queries by fetching all Contacts in a single query and then using a Map keyed by AccountId to efficiently associate them with each Account. It reduces the number of SOQL queries from potentially thousands to one, avoiding governor limits and dramatically improving page load time.

Why this answer

The correct approach is to bulkify the code by moving the SOQL query outside the loop and using a Map to correlate child records to parents. This reduces the number of queries to one, avoiding governor limits and improving performance. The other options either do not eliminate the loop query or introduce inappropriate tools.

Exam trap

The trap here is thinking that adding a LIMIT or switching to SOSL solves the loop query problem, when the real fix is to query once and correlate with a Map.

24
MCQmedium

A developer is building a Lightning Web Component that displays a list of Accounts with their related Contacts. The component currently performs a separate SOQL query for each Account to retrieve its Contacts, resulting in 200 queries when 200 Accounts are displayed. The developer wants to reduce the number of queries to improve performance and avoid hitting governor limits. Which approach should be used?

A.Use a SOQL query to retrieve all Contacts and then use Apex to group them by AccountId.
B.Use a single SOQL query with a subquery to retrieve Accounts and their related Contacts.
C.Use a separate SOQL query for each Account but cache the results in Platform Cache to reduce database calls.
D.Use Database.query with a bind variable to retrieve all Accounts and then use a Map to associate Contacts.
AnswerB

A single SOQL query with a subquery (e.g., SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account) retrieves all parent and child records in one query, reducing the number of queries to 1. This is efficient and well within governor limits, as the subquery counts as part of the same query. It avoids the N+1 query problem and is a standard performance optimization for related data.

Why this answer

Using a single SOQL query with a subquery retrieves both parent and child records in one call, eliminating the N+1 query problem. This approach is efficient, respects governor limits, and is the recommended pattern for displaying related records in Lightning Web Components. It ensures that only the necessary data is retrieved and reduces round trips to the database.

Exam trap

The trap here is assuming that caching or client-side grouping can replace a proper relationship query, when the real issue is the number of database round trips within a single transaction.

25
MCQhard

A developer is designing a solution to calculate real-time statistics on a high-volume custom object, `Sensor_Reading__c`, which receives thousands of new records per hour. The statistics must be displayed on a Lightning Web Component (LWC) dashboard and must reflect the most recent data within 5 minutes. The developer considers using a scheduled Apex job to aggregate data every 5 minutes, but the aggregation query takes longer than 5 minutes to run. What is the most appropriate approach to meet the performance requirement?

A.Create a formula field on Sensor_Reading__c that calculates the statistics dynamically and reference it in the LWC.
B.Implement a Change Data Capture (CDC) event subscriber that updates a custom summary object in real time as new Sensor_Reading__c records are inserted.
C.Use a Platform Cache to store the aggregated statistics and refresh it asynchronously using a Queueable job triggered by a record-triggered flow.
D.Use a Batch Apex job with a scope size of 1 to process each new record individually and update the summary object.
AnswerB

Change Data Capture publishes events when records change, allowing a subscriber to process each new record and update a summary object incrementally. This avoids running a heavy aggregation query and keeps statistics up-to-date in near real-time, well within the 5-minute window. It is scalable and efficient for high-volume data.

Why this answer

Change Data Capture (CDC) allows real-time streaming of record changes. By subscribing to CDC events for `Sensor_Reading__c`, the developer can incrementally update a summary object as each new reading is inserted, avoiding the need for a long-running aggregation query. This meets the 5-minute freshness requirement and scales with high volume.

Other options either rely on slow batch processing or incorrect use of formula fields.

Exam trap

The trap here is assuming that scheduled aggregation or batch processing can meet near real-time requirements, when the underlying query is too slow. Incremental processing via CDC is the key.

26
MCQeasy

A developer is building a Visualforce page that displays a table of 1,000 Contact records. The page uses a standard controller with an extension that queries all Contacts in the constructor. Users report that the page loads slowly. Which change should the developer make to improve performance?

A.Use a StandardSetController to enable pagination and reduce the number of records displayed per page.
B.Add a rendered attribute to the table to conditionally display it after the page loads.
C.Increase the view state by storing all Contacts in a transient variable.
D.Use JavaScript remoting to load the Contacts asynchronously after the page renders.
AnswerA

StandardSetController provides built-in pagination, allowing the page to display a subset of records at a time. This reduces the initial query size and the amount of data rendered, significantly improving load time. It also handles sorting and navigation efficiently, making it ideal for large data sets in Visualforce.

Why this answer

StandardSetController is designed for paginating large data sets in Visualforce. By limiting the number of records per page, it reduces the initial query size and the amount of data rendered, leading to faster page loads. It also provides built-in navigation and sorting, making it a straightforward solution for improving performance.

Exam trap

The trap here is assuming that asynchronous loading or view state reduction can fix slow page loads caused by querying and rendering too many records at once, when the real solution is to limit the number of records displayed through pagination.

27
Multi-Selecthard

A developer is optimizing an Apex batch job that processes millions of records and must stay within governor limits while finishing in a reasonable time. Which TWO techniques improve performance and scalability for this batch job? (Choose two.)

Select 2 answers
A.Increase the batch size to the maximum so fewer total transactions are needed.
B.Call Database.executeBatch from within the execute method to parallelize the work.
C.Perform all DML inside the start method so the execute method only reads data.
D.Reduce the batch size so each execute method handles fewer records, lowering heap and CPU usage per transaction.
E.Use Database.QueryLocator in the start method so the query can iterate over large result sets without hitting the 50,000-row SOQL limit.
AnswersD, E

Smaller batch sizes reduce the number of records processed per execute transaction, which lowers heap consumption and CPU time per chunk and makes it less likely that an individual transaction exceeds limits. It also lets the job recover more gracefully because only one batch fails if an error occurs, rather than the entire chunk. The trade-off is more transactions, but for heap-bound jobs this is often the right lever.

Why this answer

QueryLocator in the start method lets the batch stream very large result sets beyond the standard SOQL row limit, and a smaller batch size keeps each execute transaction under heap and CPU limits. Together they make a millions-of-records job complete reliably within governor constraints.

Exam trap

The trap here is thinking that a bigger batch size always means better performance, when per-transaction governor limits make smaller chunks safer for large jobs.

28
MCQhard

A developer is optimizing a Visualforce page that displays a table of 1,000 custom object records. The page uses a StandardSetController and currently loads all records at once, causing slow rendering. The developer wants to implement pagination to improve performance. Which approach should be used?

A.Use an <apex:repeat> component with a rendered attribute to conditionally display only a subset of records based on a counter.
B.Replace the StandardSetController with a custom controller that uses SOQL OFFSET to fetch records for each page.
C.Enable view state and set the page's cache attribute to true to store all records in the browser cache.
D.Set the page size to 20 and use the StandardSetController's next() and previous() methods to navigate pages.
AnswerD

StandardSetController supports pagination through its setPageSize method and navigation methods like next() and previous(). Setting a smaller page size reduces the number of records rendered per page, improving load time. This is the intended use of StandardSetController for paginated data display in Visualforce, and it efficiently manages record retrieval.

Why this answer

StandardSetController is designed for pagination in Visualforce. By setting a smaller page size, only a subset of records is rendered at a time, reducing page load and rendering time. Navigation methods handle fetching subsequent pages efficiently.

This is the recommended approach for displaying large datasets in Visualforce pages without hitting view state limits.

Exam trap

The trap here is thinking that conditional rendering or custom OFFSET queries are equivalent to true pagination, when they either still load all data or cause database inefficiency.

29
MCQmedium

Refer to the exhibit. The query is performing poorly on an object with 5 million records. What is the most likely cause, and how should it be addressed?

A.The query is selecting too many fields and should use SELECT *.
B.Filtering on a related object field is causing a full table scan.
C.The batch size is too small, causing excessive API calls.
D.The query needs to be converted into a subquery using a nested SELECT.
AnswerB

Filtering on fields of related objects can cause the query optimizer to perform a full scan if the relationship is not appropriately indexed. This results in slow execution times as the engine checks millions of records to determine which meet the 'Technology' industry criteria on the parent.

Why this answer

The query filters on a related object field, which can lead to inefficient joins if the field is not indexed. In Salesforce, filtering on fields from related objects often bypasses standard indexes. To optimize this, the developer should consider denormalizing data or ensuring the cross-object relationship filter is supported by an index to avoid full table scans that degrade performance significantly.

Exam trap

Candidates often blame poor SOQL performance on general data volume alone, failing to recognize that filtering across unindexed relationship fields triggers full table scans.

30
MCQmedium

A developer is writing a trigger on a custom object that processes up to 200 records at a time. The trigger currently performs a SOQL query inside a loop to retrieve related records for each record. This causes the trigger to hit governor limits. What is the best practice to refactor the trigger for performance?

A.Use a SOQL query with a subquery to retrieve related records for all trigger records in one query, then process the results in the loop.
B.Use a SOQL query with a WHERE clause that filters by the trigger records' IDs, and then loop through the results to update each record.
C.Use a SOQL query for each record but add a LIMIT clause to reduce the number of rows returned.
D.Move the SOQL query outside the loop and use a Map to correlate related records with the trigger records.
AnswerD

Bulkifying the SOQL query by moving it outside the loop and using a Map to associate related records with the trigger records is the standard best practice. This reduces the number of queries to one, avoiding governor limits and improving performance.

Why this answer

Bulkifying the SOQL query by moving it outside the loop and using a Map to correlate related records is the most efficient approach. This reduces the number of queries to one, avoiding governor limits and improving performance. Other options either do not address the root cause or introduce unnecessary complexity.

Exam trap

The trap here is thinking that adding a LIMIT clause or using a subquery solves the problem, when the core issue is performing a query inside a loop that must be bulkified.

31
MCQhard

A developer is optimizing a Visualforce page that displays a large list of Accounts with related Contacts. The page currently uses a standard controller with an <apex:pageBlockTable> and a controller extension that queries all Contacts for each Account in a loop. Users report that the page loads slowly and sometimes times out. Which technique should the developer implement to improve performance?

A.Enable lazy loading on the <apex:pageBlockTable> by setting the 'reRender' attribute to load Contacts only when a user expands a row.
B.Use a single SOQL query with a subquery to retrieve all Accounts and their Contacts, then iterate over the results to build a map for the page.
C.Implement pagination using the StandardSetController to limit the number of Accounts displayed per page, thereby reducing the number of Contacts queried.
D.Cache the Contact records in Platform Cache and retrieve them on subsequent page loads to avoid repeated queries.
AnswerB

A single query with a subquery (e.g., 'SELECT Id, Name, (SELECT Id, LastName FROM Contacts) FROM Account') retrieves all necessary data in one call. This eliminates the N+1 query problem, reduces database round trips, and avoids the SOQL query limit. The developer can then map Contacts by AccountId for efficient rendering in the Visualforce page.

Why this answer

Using a single SOQL query with a subquery to fetch Accounts and their Contacts in one call eliminates the N+1 query problem, where a separate query is made for each Account's Contacts. This reduces database load, avoids governor limits, and significantly improves page load time. The developer should then process the results into a map for efficient access in the Visualforce page.

Exam trap

The trap here is thinking that pagination or caching alone can solve the performance issue, but they do not address the underlying inefficient query pattern that causes multiple queries per record.

32
MCQhard

A developer has a Lightning Web Component that calls an Apex controller method returning 5,000 Account records to render in a custom table. Users report the component takes several seconds to become interactive. The developer wants to reduce the initial payload and rendering time. Which change is the most effective?

A.Increase the Apex heap size by setting a higher limit in the Apex class and re-deploy.
B.Wrap the entire table in lightning-datatable and pass all 5,000 records to it at once.
C.Implement pagination or infinite loading so Apex returns only the records currently needed, and use @AuraEnabled(cacheable=true) where the data is read-only.
D.Move the Apex call into a @wire property and rely on the framework to automatically chunk the results.
AnswerC

Returning only the page of records the user needs drastically shrinks the JSON payload sent over the wire and the number of DOM nodes the component must render, which is the dominant cost. Marking the method cacheable allows the client-side Lightning Data Service cache to serve repeat requests without a server round trip, further improving perceived performance for read-only data.

Why this answer

The dominant cost when rendering thousands of rows is the size of the serialized payload plus the number of DOM nodes created. Returning only the current page and marking read-only methods cacheable minimizes both transfer and render work, which is the standard Lightning Web Component performance pattern for large lists.

Exam trap

The trap here is assuming that changing the UI base component or the Apex annotation alone reduces work, when the real cost is transferring and rendering the full data set.

33
Multi-Selectmedium

A developer needs to improve the performance of a report that queries millions of records across several custom objects. The architect suggests using Skinny Tables. Which TWO statements correctly describe the benefits and limitations of Skinny Tables? (Choose two.)

Select 2 answers
A.Skinny tables can include fields from different objects, effectively acting as a pre-joined view.
B.Skinny tables do not include soft-deleted records, which reduces the volume of data scanned.
C.Skinny tables are automatically created by Salesforce for any object exceeding 1 million records.
D.Skinny tables improve performance by reducing the number of database joins required for a query.
E.Skinny tables can be created by developers directly using the Metadata API or Tooling API.
AnswersB, D

One of the primary performance advantages of skinny tables is that they exclude records in the Recycle Bin. In a standard table, the database must filter out soft-deleted records during a query. By omitting these records entirely, skinny tables allow the database to scan a smaller, more relevant dataset, improving speed.

Why this answer

Skinny tables are a specialized performance feature in Salesforce that improve query performance by mapping frequently used fields into a separate table. This table contains only the necessary columns, reducing the number of joins required and the overall amount of data scanned. They are particularly useful for large tables but require support assistance for creation and maintenance.

Exam trap

Candidates often assume skinny tables are for storage optimization or general performance, ignoring the fact that they primarily exist to reduce join overhead and exclude soft-deleted records.

34
MCQmedium

A developer is writing a batch Apex class to process 50,000 Account records. To ensure optimal performance and avoid hitting governor limits, which strategy should be implemented regarding DML operations?

A.Perform DML operations inside the loop to ensure immediate data updates.
B.Call the Database.update() method for every individual record in the scope.
C.Collect modified records into a List and perform a single DML operation after the loop.
D.Use the Future method to update each record asynchronously.
AnswerC

Bulkifying DML operations by collecting records into a list and performing one update statement after the loop is a best practice. This approach minimizes the total number of DML statements used per batch execution, staying well within governor limits and significantly improving overall processing time.

Why this answer

Batch Apex should always perform DML operations outside of the loop iterating over the scope records. By collecting records in a List and performing a single DML operation after the loop finishes, the developer significantly reduces the number of DML statements consumed. This pattern is critical for scalability in Salesforce, as it prevents hitting the 150 DML limit per transaction while maximizing bulkification efficiency.

Exam trap

Candidates often perform DML inside the loop, which is a common error that leads to hitting the 150 DML statement governor limit when processing large batches of records.

35
MCQeasy

When designing a high-performance integration, what is the best practice for handling data updates to avoid record locking issues?

A.Process records in random order to distribute load.
B.Perform all updates using a single user account.
C.Sort data by record ID before performing bulk DML operations.
D.Disable all triggers during the bulk data update process.
AnswerC

Sorting by ID ensures that all threads or processes lock records in the same order, which is the standard technique for preventing deadlocks and row locking contention in Salesforce. This approach is highly recommended when handling large-scale data updates to ensure the stability and reliability of the integration.

Why this answer

Sorting data by ID before performing bulk updates is the most effective way to prevent record locking contention. When records are processed in a consistent order, multiple threads or processes are less likely to conflict, as they will attempt to lock records in the same sequence. This simple optimization prevents 'Unable to lock row' errors, which are common in high-volume, multi-threaded integration environments.

Exam trap

Candidates often try to use 'FOR UPDATE' locks or complex try-catch blocks to handle row contention, ignoring the fact that record ordering is the primary preventative measure.

36
MCQmedium

A developer is building a Lightning Web Component that needs to display a list of 200 accounts with their annual revenue, and the component's Apex controller currently executes a SOQL query inside a loop over the accounts to fetch related opportunities. Users report slow load times. What is the most effective way to improve performance?

A.Increase the query batch size by using Database.getQueryLocator with a higher scope size.
B.Move the SOQL query into a future method to run asynchronously, and then poll for results.
C.Use a single SOQL query with a subquery to retrieve accounts and their related opportunities in one call, then process the results in memory.
D.Add a @AuraEnabled(cacheable=true) annotation to the Apex method to enable client-side caching.
AnswerC

A single SOQL query with a subquery eliminates the N+1 query problem, drastically reducing database round trips and governor limit consumption. For 200 accounts, one query returns all related opportunity data, which can be processed in memory. This is the most efficient approach and aligns with Salesforce best practices for bulk data retrieval.

Why this answer

The performance bottleneck is the N+1 query pattern: one query for accounts, then a separate query for each account's opportunities. Consolidating into a single query with a subquery eliminates the repeated database calls, reduces governor limit usage, and speeds up the component. Processing in memory is efficient because the data volume is manageable.

Exam trap

The trap here is assuming that client-side caching or asynchronous processing will fix slow initial loads, when the real issue is the inefficient query pattern inside a loop.

37
MCQmedium

A developer has built a Lightning Web Component that calls an Apex controller method to retrieve a list of Opportunities for a given Account. The SOQL query uses an indexed field on the Opportunity object, but the query still times out for Accounts with over 100,000 related Opportunities. The developer wants to improve performance by reducing the amount of data transferred and processed. Which approach should the developer take?

A.Use SOQL OFFSET to paginate through the Opportunity records in chunks.
B.Increase the query timeout by setting a higher value in the Apex controller.
C.Implement pagination using a custom cursor or Keyset pagination with the Id field.
D.Use a SOQL query with a FOR UPDATE clause to lock the records and speed up retrieval.
AnswerC

Keyset pagination uses a WHERE clause with the last seen Id (e.g., WHERE Id > :lastId ORDER BY Id LIMIT 200) to fetch the next set of records. This leverages the indexed Id field and avoids scanning skipped rows, making it efficient even for large datasets. It reduces data transfer and processing per request, directly addressing the timeout issue.

Why this answer

Keyset pagination, also known as seek pagination, uses an indexed column (such as Id) to retrieve the next page of results without scanning previous rows. This method is highly efficient for large datasets because it avoids the performance degradation of OFFSET and limits the number of rows returned per call. By fetching only a small batch, it reduces both data transfer and processing, alleviating timeouts.

Exam trap

The trap here is assuming that increasing timeout settings or using OFFSET can solve performance issues with large related lists, when in fact only efficient pagination techniques like keyset pagination address the root cause.

38
MCQhard

A developer is optimizing a Visualforce page that displays a large table of Opportunity records. The page uses a StandardSetController and iterates over the records to display fields. Users report that the page loads slowly, and the developer notices that the page makes a SOQL query for each Opportunity to retrieve the Owner's Name. The developer wants to improve performance by reducing the number of queries. What is the most efficient way to achieve this?

A.Create a formula field on Opportunity that references the Owner's Name and display that field in the Visualforce page.
B.Enable lazy loading on the Visualforce page so that Owner's Name is loaded only when the user scrolls to that row.
C.Use a Platform Cache to store the Owner's Name for each Opportunity and retrieve it from the cache instead of querying.
D.Use a SOQL query with a relationship query to retrieve the Owner's Name along with the Opportunity records in the StandardSetController.
AnswerD

Using a relationship query (e.g., SELECT Id, Name, Owner.Name FROM Opportunity) in the StandardSetController's query retrieves the Owner's Name in the same query as the Opportunities. This eliminates the need for additional queries for each Opportunity, reducing the total number of queries and improving page load time. It is the most efficient way to fetch related data.

Why this answer

The performance issue is caused by the page making a separate SOQL query for each Opportunity to get the Owner's Name. By using a relationship query in the StandardSetController, the Owner's Name is retrieved in the same query as the Opportunities. This reduces the total number of queries to one, significantly improving page load time.

The other options either do not reduce queries or add unnecessary complexity.

Exam trap

The trap here is thinking that caching or formula fields can replace the need for a relationship query, when the simplest and most efficient solution is to fetch related data in the initial query.

39
MCQeasy

A developer is troubleshooting a Lightning Web Component that calls an Apex method returning many records and notices the component re-fetches the same data every time the user navigates back to the tab. The developer wants to avoid redundant server calls for read-only data. Which change should be made?

A.Store the Apex results in a static variable in the controller so subsequent calls return the cached list.
B.Annotate the Apex method with @AuraEnabled(cacheable=true) and call it through a @wire adapter or wired property.
C.Move the Apex logic into a Flow and invoke the Flow from the component on each render.
D.Add @AuraEnabled(cacheable=false) and call the method imperatively on every connectedCallback.
AnswerB

Marking a read-only Apex method cacheable and consuming it through @wire lets Lightning Data Service cache the response on the client. When the user returns to the tab, the cached data can be reused instead of issuing a new server call, which reduces redundant round trips. Cacheable methods must not perform DML, which fits the read-only requirement.

Why this answer

Client-side caching for read-only Apex is provided by marking the method cacheable and consuming it through @wire, which routes through Lightning Data Service. That lets the framework reuse previously fetched data instead of issuing a new server call each time the component loads, directly eliminating the redundant fetches described.

Exam trap

The trap here is assuming an Apex static variable caches data across requests, when static state only survives within a single transaction.

40
MCQmedium

A developer wants to use Platform Cache to improve the performance of a high-traffic Visualforce page that performs expensive SOQL queries and calculations. The data is specific to each user and should persist across multiple requests within the same session. Which type of cache should the developer use?

A.Org Cache, because it allows all users to share the same cached data.
B.Session Cache, because it is dedicated to an individual user's session.
C.Distributed Cache, because it automatically syncs data across all instances.
D.Metadata Cache, because it is optimized for SOQL query result sets.
AnswerB

Session Cache stores data that is tied to a specific user's session. It is the correct choice for this scenario because it allows the developer to cache the results of expensive calculations only for that user. This ensures that the data is reused across multiple requests by the same user, improving their specific experience.

Why this answer

Platform Cache is divided into Org Cache and Session Cache. Session Cache is specifically designed to store data associated with a single user's session. This is ideal for scenarios where data is expensive to compute but unique to a user, as it prevents redundant processing across multiple page loads or requests within that session.

Exam trap

Candidates frequently confuse Org Cache with Session Cache, failing to recognize that user-specific data persistence across requests specifically requires the Session Cache implementation.

41
MCQmedium

A developer needs to update a field on 50,000 child records based on a change in a parent Account. What is the most performant way to handle this update?

A.Use a trigger to perform the update synchronously.
B.Implement a Batch Apex class to update in chunks.
C.Use a flow with a loop and record update element.
D.Use the @future method in a recursive loop.
AnswerB

Batch Apex processes the 50,000 records in smaller, manageable chunks, typically 200 at a time. This keeps the execution within the governor limits for each batch, allowing the entire job to complete successfully without hitting the DML limit or exhausting the CPU time allocated to a single transaction.

Why this answer

Updating 50,000 records requires careful consideration of governor limits. Batch Apex is designed specifically for this use case, as it processes records in chunks, managing the governor limits for each batch independently. This ensures the transaction does not exceed heap, DML, or CPU limits, providing a robust and reliable way to perform mass data updates without interrupting normal system operations or causing timeouts.

Exam trap

Many candidates incorrectly select Queueable Apex or standard trigger logic for massive updates of 50,000 records, forgetting that Batch Apex is specifically built for large volume data processing.

42
Multi-Selecthard

A developer is optimizing a Visualforce page that displays a large list of Opportunities with related OpportunityLineItems. The page currently uses a standard controller with an `<apex:pageBlockTable>` and a SOQL query in the controller that retrieves all Opportunities and their line items. The page loads slowly and sometimes hits governor limits. Which two strategies should the developer use to improve performance? (Choose two.)

Select 2 answers
A.Use `@AuraEnabled` methods to retrieve data via Lightning Data Service instead of a Visualforce controller.
B.Move the SOQL query to a future method to run asynchronously.
C.Implement pagination using `StandardSetController` to limit the number of records displayed per page.
D.Use `SOQL` with `FOR UPDATE` to lock records and prevent concurrent updates.
E.Reduce the view state by using `transient` keyword for non-essential controller variables.
AnswersC, E

Using `StandardSetController` with pagination reduces the number of records retrieved and rendered at once, decreasing view state size and improving load time. It also helps avoid hitting governor limits by processing smaller batches. This is a standard best practice for handling large data sets in Visualforce.

Why this answer

Implementing pagination with `StandardSetController` limits the number of records loaded and displayed, reducing view state and governor limit risks. Marking non-essential controller variables as `transient` reduces view state size, which directly improves page load time. Both strategies address the core performance issues of large data sets in Visualforce.

Exam trap

The trap here is confusing Visualforce optimizations with Lightning-specific techniques, such as Lightning Data Service or @AuraEnabled methods, which are not applicable to Visualforce pages.

43
MCQhard

A developer is writing an Apex trigger that should only fire when specific fields are changed. Which THREE practices help optimize the trigger's performance?

A.Check field values in the trigger to avoid redundant logic.
B.Move business logic into a separate service class.
C.Perform all DML operations inside the trigger loop.
D.Use the 'if' condition to exit early if criteria are not met.
E.Execute all SOQL queries for every record in the trigger.
AnswerA, B, D

Comparing the old and new field values is a crucial optimization step. It prevents the trigger from running expensive logic when no relevant fields have been modified, effectively reducing the CPU usage and ensuring the code remains performant for bulk operations where only a few records might change.

Why this answer

Trigger optimization is essential for preventing unnecessary processing. By checking if fields have actually changed, the developer avoids executing logic when no relevant data updates have occurred. Furthermore, decoupling logic into service classes keeps the trigger thin and manageable, while early-exit patterns ensure the code finishes as fast as possible if conditions aren't met, maintaining high system throughput and preventing governor limit issues.

Exam trap

Many developers write monolithic trigger code and fail to include early-exit criteria, causing triggers to execute redundant logic on every single record modification.

44
Multi-Selectmedium

A developer is optimizing a complex Apex transaction that processes a large number of records. The transaction currently performs multiple SOQL queries and DML operations inside loops. Which two strategies should be used to improve performance and avoid governor limit errors? (Choose two.)

Select 2 answers
A.Collect records in a list and perform a single DML operation after the loop instead of DML inside the loop.
B.Use @future annotation on the method to run the DML asynchronously and avoid limits.
C.Increase the heap size by using the Limits.getHeapSize() method to monitor and adjust.
D.Use Database.insert with the allOrNone parameter set to false to allow partial success and continue processing.
E.Move SOQL queries outside of loops and use a single query to retrieve all necessary records.
AnswersA, E

Performing DML inside a loop causes multiple database operations, quickly hitting the DML governor limit (150 statements) and degrading performance. Collecting records in a list and executing one DML operation after the loop is the recommended bulkification pattern. This reduces database round trips and improves transaction speed.

Why this answer

The two key strategies are to move SOQL queries outside of loops and to consolidate DML operations. These practices, known as bulkification, minimize database round trips and governor limit consumption. They are essential for processing large data volumes efficiently in Apex.

The other options either do not address the root cause or are not valid optimizations.

Exam trap

The trap here is focusing on error handling or asynchronous processing instead of the core bulkification techniques that directly reduce governor limit usage.

45
MCQmedium

What is the primary benefit of using a Platform Cache for application data?

A.It provides permanent storage for large files like images.
B.It eliminates the need for writing any SOQL queries.
C.It reduces latency by storing frequently accessed data in memory.
D.It automatically synchronizes data with external systems.
AnswerC

Platform Cache serves data directly from memory, which is much faster than querying the database. By reducing the reliance on SOQL or API calls, it significantly decreases latency and CPU consumption, providing a seamless user experience even under heavy load, which is critical for performance-optimized Salesforce applications.

Why this answer

Platform Cache provides a high-speed, in-memory storage layer that allows developers to cache frequently accessed data. This significantly reduces the need for expensive SOQL queries or API calls, resulting in faster response times and lower CPU usage. By storing data in the cache, the application becomes more efficient and scalable, especially when handling high-frequency access to static or semi-static information.

Exam trap

Candidates often confuse Platform Cache with browser-side caching, failing to realize that Platform Cache is a server-side, Org-wide memory store intended for reducing database query overhead.

46
MCQhard

A developer is optimizing a Lightning Web Component that displays a list of 500 custom object records. The component uses a wire adapter to call an Apex method that returns the records. The Apex method currently queries all fields on the custom object, including several rich text fields and formula fields that are not displayed in the component. Users report that the component takes a long time to load. What should the developer do to improve the performance of the Apex method?

A.Use a SOQL query that selects only the fields required by the Lightning Web Component, avoiding unnecessary fields.
B.Use a SOQL query with a LIMIT clause to reduce the number of records returned to 100.
C.Use the @AuraEnabled(cacheable=true) annotation on the Apex method to enable client-side caching.
D.Increase the cacheable scope of the Apex method to 'global' to cache the results across all users.
AnswerA

Selecting only the necessary fields reduces the amount of data transferred from the database to the Apex method and then to the client. Rich text and formula fields can be expensive to compute and transfer. By querying only the fields needed for display, the developer minimizes heap usage and improves response time. This is a best practice for optimizing SOQL queries.

Why this answer

The Apex method is slow because it queries all fields, including expensive rich text and formula fields that are not displayed. Selecting only the required fields reduces the data volume and computation, improving performance. Caching or limiting records does not address the root cause and may alter functionality.

The best solution is to optimize the SOQL query to fetch only the needed fields.

Exam trap

The trap here is focusing on caching or limiting records as performance fixes, when the real issue is querying unnecessary fields that increase data transfer and computation.

47
MCQhard

Refer to the exhibit. The Apex transaction is consistently hitting the CPU limit. What is the most likely cause and the best way to optimize the code?

A.Replace nested loops with Map-based lookups.
B.Reduce the batch size in the Batch Apex class.
C.Increase the CPU limit in the organization configuration.
D.Use the 'transient' keyword for all variables.
AnswerA

Nested loops are computationally expensive, with a time complexity of O(n*m). Replacing these with a Map allows for constant time O(1) lookups, which drastically reduces the CPU cycles required for data processing. This is the most effective way to optimize logic that is causing CPU limit issues.

Why this answer

The CPU time limit is reached when the Apex code performs too many calculations, loops, or complex logic within a single transaction. Optimization requires reducing the complexity of the code, such as moving away from nested loops, using maps for faster lookups, or offloading heavy computations to asynchronous processes like Batch Apex or Queueable Apex. This ensures that the transaction completes within the time limit allocated by the platform.

Exam trap

Students often confuse CPU limits with heap limits, mistakenly suggesting memory optimization strategies like chunking when the actual bottleneck stems from inefficient algorithmic complexity.

48
MCQmedium

An enterprise Salesforce application requires high-performance execution of complex SOQL queries across millions of records. Which strategy should a developer implement to ensure optimal query performance and prevent governor limit violations?

A.Write dynamic SOQL strings concatenating user inputs to filter datasets flexibly.
B.Apply custom indexes on frequently filtered fields and ensure filters use selective criteria.
C.Retrieve all records into an Apex collection and filter them using nested loops.
D.Wrap every SOQL query in a try-catch block to automatically fallback to unindexed searches.
AnswerB

Custom indexes allow the database query engine to instantly locate record subsets without scanning entire tables. When queries use selective filters matching indexed fields, database statistics optimize execution paths, drastically reducing query execution times and preventing timeout errors.

Why this answer

Utilizing selective queries with custom indexes combined with proper bind variables ensures that database operations avoid full table scans. This optimization directly prevents CPU time and query row limit exceptions, protecting platform resources and maintaining user experience under heavy transaction loads.

Exam trap

Candidates often rely on adding more filter conditions without checking index status, leading to expensive full table scans on large data volumes.

49
MCQhard

A developer is building a batch Apex class to process 1 million records. The class implements Database.Batchable and uses a SOQL query in the start method. During testing, the developer notices that the batch job fails with a 'First error: Exceeded maximum number of SOQL queries' error. What is the most likely cause and how can it be resolved?

A.The execute method contains a SOQL query inside a loop; move it outside the loop and use a Map.
B.The start method uses a QueryLocator; switch to an Iterable to avoid query limits.
C.The query in the start method is not selective; add a WHERE clause to filter records.
D.The batch size is too large; reduce the batch size to 1 to avoid query limits.
AnswerA

Batch Apex allows up to 200 SOQL queries per transaction. If the execute method queries inside a loop, it can quickly exceed this limit. Moving the query outside the loop and using a Map to correlate records is the standard fix. This bulkifies the code and prevents governor limit errors.

Why this answer

The most likely cause is a SOQL query inside a loop in the execute method, which quickly exceeds the 200 SOQL query limit per transaction. Moving the query outside the loop and using a Map to correlate records resolves the issue by reducing the number of queries to one per batch transaction. The other options do not address the root cause.

Exam trap

The trap here is focusing on the start method or batch size, when the real issue is a query inside a loop in the execute method that exceeds the SOQL query limit.

50
MCQmedium

A developer wants to minimize the impact of long-running operations on the user interface. Which design pattern should they utilize?

A.Implement @future methods for every database update.
B.Use Queueable Apex to offload complex tasks to the background.
C.Use Platform Events to perform synchronous calculations.
D.Write the logic in JavaScript to execute on the client side.
AnswerB

Queueable Apex provides a robust way to chain and monitor asynchronous jobs. It is more flexible than @future methods and is the recommended approach for offloading non-critical, long-running operations, keeping the UI responsive while ensuring the backend work is completed reliably and in the correct order.

Why this answer

Asynchronous processing, such as Queueable Apex, offloads heavy tasks to the background. By executing long-running logic outside the main user request thread, the UI remains responsive. This improves the perceived performance of the application significantly, as users do not have to wait for complex computations to finish before continuing their work in the Salesforce interface.

Exam trap

Candidates tend to confuse Scheduled Apex with Queueable Apex, choosing scheduled execution when the requirement is specifically to unblock the user interface immediately.

51
MCQmedium

A developer is writing a query to fetch related records. Which SOQL pattern is best for avoiding unnecessary query execution and improving performance?

A.Perform separate queries for each record inside a loop.
B.Use a single relationship query to fetch parent and child records.
C.Cache all retrieved data in a static Map variable.
D.Use the 'FOR' loop with the 'LIMIT' keyword.
AnswerB

Relationship queries allow the retrieval of related data in one statement. This approach is highly efficient because it eliminates the need for repeated database calls, staying within governor limits and significantly reducing execution time compared to multiple individual queries performed in a loop or sequentially.

Why this answer

Using relationship queries (joins) allows fetching data from parent and child objects in a single SOQL statement. This prevents the 'query-in-a-loop' anti-pattern, which is the most common cause of hitting the 100 SOQL query limit. By retrieving all necessary data at once, the developer reduces the number of server round-trips and keeps the transaction lightweight and performant, which is essential for scaling code in an enterprise environment.

Exam trap

Candidates often select multiple individual queries or map iterations instead of realizing that a single parent-to-child relationship query natively resolves query-in-a-loop anti-patterns.

52
MCQhard

A developer is optimizing a complex SOQL query that joins multiple custom objects. The query is used in a trigger and is causing CPU time limit exceptions. The developer notices that the query is not using any indexes. What is the most likely cause?

A.The query uses a relationship subquery that exceeds the maximum allowed depth.
B.The query includes a WHERE clause on a field that is not indexed.
C.The query is using a NOT operator in the WHERE clause.
D.The query is selecting too many fields, causing high CPU usage.
AnswerB

SOQL queries rely on indexes to efficiently filter records. If the WHERE clause references a field without a custom index, the query performs a full table scan, consuming excessive CPU time. This is especially problematic in triggers where CPU limits are strict. Adding a custom index on the filtered field can dramatically improve performance and prevent CPU time exceptions.

Why this answer

The most likely cause of a SOQL query not using an index is that the WHERE clause filters on a field without a custom index. This forces a full table scan, leading to high CPU consumption and potential governor limit exceptions. Adding a custom index on the filtered field can resolve the issue.

Other options are either less common or do not directly explain the lack of index usage.

Exam trap

The trap here is assuming that any complex query automatically uses indexes, when in fact index usage depends on the fields in the WHERE clause.

53
MCQmedium

A developer is building a search feature that must query across multiple objects. What is the most performant approach to searching for a term that might exist in any field?

A.Run multiple SOQL queries and combine the results in Apex.
B.Use a SOSL query to perform a multi-object search.
C.Implement a custom Apex search using a loop over all records.
D.Query the Setup Audit Trail object for search results.
AnswerB

SOSL is designed for searching multiple objects simultaneously by utilizing pre-built indexes on text fields. It is significantly faster than executing individual SOQL queries, especially when the search scope spans several objects, making it the standard choice for building efficient, high-performance search features in Salesforce.

Why this answer

SOSL is optimized specifically for full-text searching across multiple objects. Unlike SOQL, which is designed for structured data retrieval and field filtering, SOSL indexes text fields to return results quickly. Using SOSL ensures that the search functionality remains performant as record volumes increase, preventing the performance degradation that would occur if multiple SOQL queries were executed sequentially to achieve the same result.

Exam trap

Candidates frequently choose SOQL with multiple OR filters across different objects, which is syntactically impossible in a single query and leads to inefficient, multiple database round-trips.

54
MCQmedium

A developer is building an Apex trigger on a high-volume custom object that must update a related child record whenever a parent record's Status__c changes. The trigger runs for both single-record UI edits and bulk API loads of 200 records. The developer wants to avoid a per-record SOQL query inside the trigger loop. Which approach is the most performant and scalable?

A.Rely on a formula field on the child that references the parent's Status__c so no query is required in the trigger.
B.Use Database.query() inside the loop with a dynamically built WHERE clause for each parent record.
C.Move the child query outside the loop and use a Map keyed by the parent Id, then iterate the trigger records against that Map.
D.Add a SOQL query inside the loop that filters on the current record's Id to fetch the matching child.
AnswerC

Querying the related child records once before the loop, storing them in a Map keyed by the parent relationship Id, and then iterating Trigger.new against that Map removes the per-record query from the loop. This keeps the code bulk-safe, avoids hitting the 100 SOQL query governor limit, and scales to 200-record batches without additional DML or query overhead.

Why this answer

Collecting the related children in a single query before the loop and indexing them by parent Id in a Map eliminates per-record SOQL, keeping the trigger within governor limits and bulk-safe. This pattern is the standard bulkification technique for parent-to-child updates and scales correctly for both single-record and 200-record API transactions.

Exam trap

The trap here is assuming that moving a query into a helper method or using dynamic SOQL changes the governor limit, when any query executed once per loop iteration still consumes one SOQL query per record.

55
MCQmedium

A developer has a requirement to update 5,000 records in a single transaction. The operation frequently hits the 'Too many DML statements' limit. What is the most efficient way to refactor the code?

A.Use the Database.upsert method inside the loop.
B.Add the 'future' annotation to the update method.
C.Collect records in a list and perform one DML statement after the loop.
D.Increase the DML governor limit using the Apex setup menu.
AnswerC

Performing a single DML statement on a list of records is the standard pattern for bulkifying Apex code. This approach uses only one of the 150 allowed DML statements, allowing the transaction to handle larger record volumes efficiently while significantly reducing the load on the database engine.

Why this answer

Governor limits enforce boundaries on DML statements within a single transaction to ensure platform stability. Performing DML inside a loop is a violation of best practices because each statement counts against the limit. Refactoring the code to collect records in a list and performing a single DML operation outside the loop reduces the number of statements from 5,000 to one, ensuring the code remains scalable and efficient for large datasets.

Exam trap

Candidates often choose solutions involving asynchronous processing for simple bulk updates, or mistakenly think using a Map instead of a List will solve DML statement limit violations inside a loop.

Ready to test yourself?

Try a timed practice session using only Performance questions.