All Around Microsoft Dynamics Business Central
While investigating the Business Central 26 CallStack performance improvements, I stumbled upon an interesting question: Does the TryFunction attribute add significant overhead when there are simpler alternatives?
The answer might surprise you.
I created two simple functions to compare the performance of different error handling approaches:
local procedure GetNonExistingCustomerTryFunction()
begin
if TryGetCustomer() then
Message('Test!');
end;
[TryFunction]
local procedure TryGetCustomer()
var
Customer: Record Customer;
begin
Customer.Get('NONEXIST');
end;
local procedure GetNonExistingCustomerGet()
begin
if GetCustomer() then
Message('Test!');
end;
local procedure GetCustomer(): Boolean
var
Customer: Record Customer;
begin
exit(Customer.Get('NONEXIST'));
end;
After 500 executions of each approach, here are the measured times:
That's a 6.3x performance difference! 🚀
The TryFunction attribute in AL is designed to suppress errors and return a boolean indicating success or failure. However, this error handling mechanism comes with significant overhead:
When you're dealing with operations that naturally return a boolean (like Record.Get()), using TryFunction adds unnecessary complexity and performance cost.
If a function naturally returns a boolean result (like Get(), Find(), Insert(), etc.), use it directly:
if Customer.Get(CustomerNo) then
// Handle success
else
// Handle not found
Reserve TryFunction for situations where you need to catch actual errors:
[TryFunction]
local procedure TryComplexOperation()
begin
// Code that might throw various errors
// that you want to handle gracefully
end;
Let's put this into perspective:
In batch operations or frequently called code paths, this overhead accumulates quickly. If you're processing thousands of records, the difference between 118ms and 743ms per 500 operations becomes very significant.
This discovery relates directly to my previous post about CallStack performance improvements. Both findings highlight how error handling mechanisms in Business Central can have substantial performance implications:
The pattern is clear: error handling infrastructure has a cost, and we should be mindful of when we really need it.
While TryFunction is a valuable tool in AL for error handling, it's not free. Before wrapping every operation in a TryFunction:
Sometimes, the simplest solution is also the fastest one.