Performance Testing Techniques
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 9 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Advanced Performance Testing for AL (Application Language) Solutions
Introduction: Why Performance Matters in Business Central
When we talk about developing solutions in AL for Dynamics 365 Business Central, we often focus on functionality—getting the data to save correctly, ensuring the calculation logic is accurate, or building a clean user interface. However, a feature that works perfectly in a sandbox environment with a handful of records can become a significant bottleneck once it hits a production database containing millions of ledger entries. Performance testing is the practice of evaluating how your code behaves under load, identifying latency issues, and ensuring that the system remains responsive for the end user.
Performance issues in the cloud-based SaaS environment of Business Central are particularly critical because you do not have direct access to the underlying SQL server to tune indexes or force query plans. Instead, you are limited by the resources allocated to your tenant and the efficiency of your AL code. If your AL code is inefficient, it will consume excessive "Database Request Units" (DRUs) or hit execution timeouts, leading to sluggish pages, failed background tasks, and frustrated users. Understanding how to measure, analyze, and optimize your code is not just a technical luxury; it is a core requirement for any professional AL developer.
In this lesson, we will explore the advanced techniques required to test the performance of your AL solutions. We will move beyond simple "it feels slow" observations and dive into data-driven analysis using tools like the AL Profiler, Query objects, and telemetry monitoring. By the end of this module, you will be equipped to identify the root causes of performance degradation and implement strategies to write code that scales effectively.
Not read yet
The Fundamentals of AL Performance Measurement
Before you can optimize, you must be able to measure. Performance testing in Business Central is not about guessing; it is about quantifying the time spent on specific operations. The most important metric in the Business Central environment is the execution time of AL code and the number of database calls made.
The AL Profiler
The AL Profiler is an essential tool integrated directly into Visual Studio Code. It allows you to record the execution of a specific piece of code and view a breakdown of how much time was spent in each function. This is the "gold standard" for identifying which specific procedure is causing a lag.
To use the AL Profiler, you start a recording session, perform the task in the Business Central client, stop the recording, and then analyze the resulting .alcpuprofile file. You will see a call tree that shows:
- Total Duration: How long the entire operation took.
- Self-Time: The time spent inside a function excluding the time spent in functions called by it.
- Hit Count: How many times a specific function was executed.
Callout: Profiler vs. Debugger While the AL Debugger is used to inspect the state of variables and the logic flow step-by-step, the AL Profiler is strictly for performance analysis. Using the debugger significantly slows down the execution of code, making it an unreliable tool for measuring performance. Always use the Profiler to identify bottlenecks and the Debugger to troubleshoot logic errors.
Database Interaction Metrics
Most performance issues in Business Central are caused by excessive database interactions. Every time your code uses FINDSET, GET, or MODIFY, the system makes a request to the database. If you are doing this inside a loop, you might be performing hundreds of unnecessary round-trips to the database, which is the fastest way to kill performance.
Not read yet
Step-by-Step: Conducting a Performance Audit
If you suspect a specific process is slow, follow this structured approach to audit and diagnose the issue.
Step 1: Establish a Baseline
Before changing a single line of code, document the current performance. Run the process three times and take the average execution time. Use the AL Profiler to capture a trace. This provides you with an objective "before" state so you can prove that your eventual changes actually improved the situation.
Step 2: Analyze the Call Tree
Open the profiler output in VS Code. Look for functions with a high "Hit Count." If you see a function like GetCustomerName being called 10,000 times in a loop, you have found your primary target. Even if each individual call is fast, the cumulative time of 10,000 requests will be substantial.
Step 3: Check for "N+1" Query Problems
The "N+1" problem occurs when you fetch a set of records (1) and then, for each of those records, perform an additional query (N) to fetch related data. For example, if you are printing a report that lists 500 Sales Orders and you call Customer.Get(SalesHeader."Sell-to Customer No.") inside the loop, you are performing 501 database calls.
Step 4: Implement Optimization
Replace row-by-row processing with set-based operations. Instead of GET inside a loop, consider using a Query object to join tables or pre-fetching the data into a temporary table or a dictionary.
Step 5: Validate
After applying your changes, run the same test scenario again. Ensure that the execution time has decreased and, more importantly, check the profiler again to see if the "Hit Count" for the problematic function has dropped.
Not read yet
Best Practices for Writing Performant AL Code
Writing performant code is a habit. By following these industry-standard patterns, you can avoid common performance pitfalls during the development phase rather than trying to fix them later.
1. Minimize Database Requests
The golden rule of AL development is to touch the database as little as possible.
- Use
FINDSET(false, false): When reading data that you do not intend to modify, always usefalseparameters. This prevents the system from locking rows or preparing for updates, which is much faster. - Use
SETLOADFIELDS: If you only need two fields from a table with 50 fields, useSetLoadFields. This tells the SQL server to only retrieve the data for those specific columns, significantly reducing the amount of data transferred between the database and the application tier.
2. Leverage Query Objects
Standard table variables are great for simple lookups, but they are inefficient for reporting or complex data analysis. Query objects are compiled into optimized SQL statements that perform joins at the database level.
// Example of a Query object implementation
query 50100 "Top Sales Customers"
{
QueryType = Normal;
elements
{
dataitem(Customer; Customer)
{
column(Name; Name) { }
column(TotalSales; "Sales (LCY)") { Aggregate = Sum; }
}
}
}
By using the Query object above, you retrieve the aggregated data in a single round-trip, rather than iterating through every Sales Header and calculating the total manually.
3. Use Dictionaries and Lists
If you need to perform many lookups for the same data, do not query the database every time. Fetch the data once, store it in a Dictionary or List variable, and perform your lookups in memory. Memory operations are orders of magnitude faster than database calls.
Tip: In-Memory Caching When dealing with configuration tables or "setup" data that rarely changes, load the data into a global variable or a singleton codeunit upon the first access. This pattern ensures that subsequent requests for the same configuration data take near-zero time.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced developers fall into traps when working with complex business logic. Here are the most frequent mistakes observed in Business Central solutions.
The "Loop-Inside-a-Loop" Trap
This is the most common cause of "slow pages." If you have a nested loop, the complexity grows exponentially. If your outer loop runs 100 times and your inner loop runs 100 times, you are performing 10,000 iterations. If there is a database call inside that inner loop, the performance will be abysmal.
How to avoid it: Always look for ways to flatten the logic. Can you calculate the inner loop results using a Query or a SetRange before entering the outer loop?
Over-using ModifyAll or DeleteAll
While these functions are convenient, they trigger individual database events for every record processed. If you have "OnModify" or "OnDelete" triggers on the table, performing a ModifyAll on 5,000 records will trigger 5,000 separate pieces of logic.
How to avoid it: If you are performing bulk updates, consider if you can bypass the triggers by using ModifyAll(Field, Value, false). However, be very careful—this will ignore your business logic, so ensure it doesn't break data integrity.
Missing Table Indexes
If you are filtering a table by a field that is not indexed, the SQL server must perform a "Table Scan," which means reading every single row in the table to find the matches. On a large table, this is a performance disaster.
How to avoid it: Always ensure that your SetRange or SetFilter calls are using fields that are indexed. In Business Central, this usually means ensuring you are using the Primary Key or a Secondary Key.
Not read yet
Comparison: Traditional Coding vs. Performant Coding
The following table highlights the difference between standard development patterns and optimized approaches.
| Scenario | Traditional Approach | Optimized Approach | Performance Impact |
|---|---|---|---|
| Data Fetching | Record.Get() in a loop |
Query object or SetLoadFields |
High (Reduces round-trips) |
| Filtering | Filtering on non-indexed fields | Using keys and SetRange |
Extreme (Avoids Table Scans) |
| Calculations | Manual looping for totals | Query aggregation |
High (Moves load to SQL) |
| Lookups | Repeated Record.Get() |
Dictionary or local cache |
Medium (Reduces network I/O) |
Using Telemetry for Proactive Performance Monitoring
In the modern SaaS world, you shouldn't wait for a user to complain that a process is slow. You should be monitoring your solutions using Azure Application Insights. Business Central automatically sends telemetry data to your linked Application Insights instance, including information about:
- Long-running SQL queries: Alerts you when a query takes longer than a specific threshold (e.g., 500ms).
- AL execution time: Tracks how long specific code units take to run.
- Database locks: Identifies when multiple users are blocking each other due to record locks.
Setting Up Telemetry
- Navigate to the Business Central Admin Center.
- Link your environment to an Azure Application Insights resource.
- Use Kusto Query Language (KQL) to query the telemetry.
For example, to find all long-running SQL queries, you would run a KQL query like this:
traces
| where customDimensions.eventId == 'RT0005'
| project timestamp, customDimensions.sqlStatement, customDimensions.executionTime
| order by timestamp desc
This proactively identifies the exact SQL statement that is causing performance issues, allowing you to optimize the code before the problem becomes widespread.
Callout: Why Telemetry is Mandatory Relying on manual testing is no longer sufficient. In a cloud environment, performance can fluctuate based on the total load of the cluster. Telemetry provides the "real-world" data that your local sandbox environment cannot replicate. It captures the performance of your solution under actual user behavior and real data volumes.
Not read yet
Advanced Technique: Handling Large Data Sets
When your solution needs to process tens of thousands of records (e.g., an integration that imports 50,000 lines from an external API), standard record-based processing will fail or time out. You must use "Job Queues" and "Background Sessions."
The Pattern: Asynchronous Processing
Never force the user to wait for a 5-minute data import to finish while they are staring at a screen. Instead:
- User uploads the file.
- Code saves the file to a blob or a staging table.
- Code triggers a background task using
Codeunit.RunorJobQueue. - User receives a notification that the process has started.
- Background task processes the data and updates the status.
This keeps the UI responsive and ensures that the system remains usable for other tasks.
Batching
If you must process large amounts of data, do not attempt to process it all in one transaction. Transaction logs on the SQL server can become bloated, leading to performance degradation. Process in batches of 500 or 1,000 records, and use Commit() at the end of each batch to release locks and clear the transaction log.
// Example of batch processing
var
RecordCounter: Integer;
begin
if Rec.FindSet() then
repeat
// Perform processing
RecordCounter += 1;
if RecordCounter >= 500 then begin
Commit(); // Commit the transaction to release resources
RecordCounter := 0;
end;
until Rec.Next() = 0;
Commit(); // Final commit
end;
Not read yet
Best Practices Checklist
To ensure your AL solutions meet high-performance standards, review your code against these criteria:
- Avoid unnecessary field retrieval: Use
SetLoadFieldson all large tables. - Use
FindSet(false, false): Only usetruewhen you are absolutely certain you need to modify the record. - Reduce database round-trips: If you need to look up data from a related table, use a
Queryobject instead of looping. - Use
Dictionaryfor lookups: Cache repeated data in memory. - Implement batching: Never run long-running processes in the foreground; use background tasks.
- Monitor telemetry: Regularly check your Application Insights for long-running SQL queries.
- Verify index usage: Check that all your
SetRangeandSetFiltercalls use indexed fields.
Common Questions (FAQ)
Q: Does adding more memory to the server help Business Central performance?
A: In the SaaS environment, you do not manage the server hardware. You manage the code. Adding "more power" is not an option; you must optimize the code to be efficient within the provided constraints.
Q: Is it better to use a Record variable or a Query object for reports?
A: Always use Query objects for reports. They are designed for set-based data retrieval and are significantly faster than iterating through Record variables.
Q: Why is my OnAfterGetRecord trigger slow?
A: This trigger runs for every single line in a report or page. If you have logic inside this trigger that calls the database, you are multiplying that database call by the number of records displayed. This is a classic N+1 bottleneck.
Q: How many records are "too many" for a single transaction?
A: There is no hard number, but once you exceed 1,000 to 2,000 records, you should start considering batching your commits to prevent lock escalation and performance degradation.
Not read yet
Summary and Key Takeaways
Performance testing is an essential skill for any AL developer working with Dynamics 365 Business Central. It transforms your development process from "making it work" to "making it work efficiently at scale." Throughout this lesson, we have covered the tools, patterns, and strategies necessary to build high-performance solutions.
Key Takeaways:
- Measurement is the Foundation: Never assume where a bottleneck is. Use the AL Profiler to gather empirical evidence of which functions are consuming the most time and how many times they are being called.
- Database Efficiency is Paramount: Most performance issues stem from excessive database round-trips. Focus on minimizing requests using techniques like
SetLoadFields,Queryobjects, and in-memory caching withDictionaries. - The N+1 Problem is the Enemy: Be vigilant about code inside loops. If you find yourself performing a
GETorFINDoperation inside aREPEAT...UNTILloop, you are likely creating a performance bottleneck that will fail as the database grows. - Use Asynchronous Processing: For long-running operations, always move the work to the background. This preserves the responsiveness of the user interface and provides a better experience for the end user.
- Telemetry provides Proactive Visibility: Use Application Insights to monitor your solutions in production. This allows you to catch performance issues before they become major user complaints.
- Batching is a Safety Valve: When performing bulk updates, break the work into smaller batches and use
Commit()to manage transaction logs and database locks. - Indexes Matter: Ensure that all your filtering logic is supported by appropriate keys. A missing index on a large table is the fastest way to trigger a system-wide slowdown.
By internalizing these practices, you move away from reactive debugging and toward a proactive, architecture-first approach to performance. Remember that every line of code you write has a cost; by being intentional about how your code interacts with the database, you ensure your solutions remain robust, responsive, and reliable for your customers.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820