X++ method call performance

Microsoft’s recommendations for performance optimizations are interesting:

  • Calls between tiers (client/server) are slow.
  • Method calls are expensive. Try to reduce the number of calls. For example, don’t call the same method several times if you can store a value from the method and instead use that value.

These statements are probably true but as with all good advice it is important to know the context in which it makes sense. How slow is slow and how expensive is expensive? And should you worry about it? Let’s find out.

Test cases

In X++ there are different kinds of methods and different ways to call them. There are some interesting cases I can think of right away.

  • Static versus instance methods
  • Staying on the same tier versus calling methods across tiers
  • Calling a method on an object of a supertype (Object) instead of the exact subtype
  • Calling a method through reflection (SysDict* classes)

Test setup

Methods calls may be slow, but they’re certainly not slow enough to accurately measure the time of a single call. Repeating the exact same call a large number of times should average out any measurement errors.

The timing code is basically this:

        for (i=1; i<=maxLoop; ++i)
            // method call here

Note that the loop overhead will be included in the measurement as well. This is not really a problem because we will use the same setup for all test cases, replacing the loop body. We’re not interested in exactly how long it takes to call a method, only in performance of the cases relative to each other. Absolute execution times depend on the configuration of the system while relative differences don’t change much between different setups. It’s a bit crude but I think it will suffice.

MaxLoop is set at 100,000 and all cases are executed sequentially. To further minimize the effect of other random system activity, all tests are repeated 20 times. This means every method call is executed 2 million times. This should give a pretty good indication of relative performance.

Overhead, e.g. for constructing object, is placed outside the timer statements. All methods are empty, take no input and return nothing. That means there’s nothing but the call going on. I’m assuming that the compiler will not perform any optimizations, like inlining functions. If it does, we should see weird results.

If you want to try this yourself get the full source here (4.0 SP2).

The results

After running the test I got these results.

#CaseAvg. time (ms) for 100,000 calls
1No method (empty loop)481
2Instance method client2,347
3Instance method server14,809
4Static method client2,298
5Static method server14,825
7Call on Object on client2,367

As expected they confirm the Best Practice recommendations. Calling a method on the same tier in a loop is about 3 times slower than an empty loop. It doesn’t really matter if it’s an instance or static method, or if the variable is of the generic Object type. The values are too close together to be statistically significant.

SysDictClass is a bit slower. That makes sense because it uses 2 methods: callObject() on SysDictClass and the method on the object itself. Surprisingly it is a lot faster than twice the value of calling an object method on the same tier. It is closer to a combination of no method and a method call on the same tier. If I had to guess I would say it is because callObject() is a method in the kernel, written in C/C++ instead of X++. Maybe there is less overhead in dealing with kernel functions. Too bad we can’t include an empty kernel method in the test to verify this.

Finally, this proves methods calls across tiers are slow. Extremely slow compared to anything else. In this setup crossing a tier is about 6 to 7 times slower than staying on the same tier. Keep in mind that these methods do not take any input and return nothing. Also, the AOS and client are on the same machine. In real code with parameters, return types and network latency it will be worse.


The optimization guidelines are correct. Now should you worry about it and avoid methods? Generally not. Breaking up code in methods improves readability of the code. Adding too many temporary variables to avoid calling the same method again can become annoying too. Usually a programmer’s time is more important (and more expensive) than execution time. It’s not worth it to optimize everything.

If you stay on the same tier you can do a lot of method calls per second. Unlike this test setup, real methods have code that takes time to execute as well The time spent performing the actual method call will be insignificant in most situations. Readability and clean design trumps performance. If X++ would support some function inlining we could have the best of both worlds with minimal effort.

When crossing from client to server or vice versa, things are more complicated. As the results show this causes a significant performance hit. From the start your code should be designed to minimize traffic between tiers. A single call won’t hurt but often bad code contains a lot of subsequent calls to objects that live on the other tier, like when constructing an object and setting it up with accessor methods. In these cases it’s better to use containers and provide methods to pass all data in a single call. Simple client/server optimizations can make a huge difference. Improvements in this area are something users could actually notice themselves.

The lone semicolon

Something that confuses and annoys people when they’re learning X++, is the semicolon after variable declarations.

As you know all local variables have to be declared at the start of the function and statements are placed after that. Then comes the important part: don’t forget to always put a semicolon on a single line before the first statement.

If you don’t, your code might not compile. Sometimes it will, sometimes it won’t. And code that works now can be broken later, without touching it. A semicolon is not always required, but instead of worrying if it’s required, it’s easier to make a habit of just writing it. Even if you don’t have any local variables. Unfortunately even standard X++ code doesn’t always have this.

The reason you need that extra semicolon is because the compiler can’t always see where the variable declarations end. If you don’t help a little, it will make a guess. And it’s not very good at guessing.

While the compiler is analyzing the code it checks if the first word on a line matches the name of a type (AOT object). If it’s a type name the compiler treats the line as a variable declaration. In this case a variable name should be next.

If the first word is not a variable the compiler considers the line to be the start of a statement. In some cases it treats statements as class declarations and that causes compiler errors.

Let me explain this with some examples from the standard application (4.0 SP1). This is a method from the BOMSearch class.

server static BOMSearch newProdTable(ProdTable prodTable)
    BOMSearch BOMSearch = new BOMSearch(
    return BOMSearch;

If you remove the semicolon from line 9 you will get an error on the next line. The first line is never a problem for the compiler: a variable BOMSearch of type BOMSearch is created.

Next the compiler sees the word BOMSearch and figures, ‘I know that, it’s a class name. So this must be a variable declaration. But what’s with the .init()? That’s not allowed here.’

And there’s the compilation error.

This method from CustTable is an example of bad standard code.

void initFromCustGroup(CustGroup _custGroup)
    this.PaymTermId = _custGroup.PaymTermId;
    this.PaymSched  = PaymTerm::find(this.PaymTermId).PaymSched;

‘What do you mean, bad code? This is standard Axapta. It works just fine!’.
Yes it does… for now. Create an EDT named this and compile again. It’s broken for the same reason as the previous example.

To avoid headaches, repeat after me: always put a semicolon on a single line before the first statement.

Too bad the compiler isn’t smarter. A Best Practice check would be nice too.

The X++ way to getters and setters

This one is for all those who are new to X++ development. When learning OO programming we’re told that encapsulation is important. Data members (variables) should be hidden and any access should go through methods. Then the typical combination of getters and setters is introduced. You’re supposed to write methods for each thing you want to expose: getSomething() and setSomething(someValue).

In X++ we do this too… with a twist. For starters, all data members of a class (variables in the ClassDeclaration) are protected. So only the class itself and subclasses can access them directly. This means X++ forces you to write methods to access data from outside the class hierarchy. Unlike other mainstream languages such as Java, C# or C++ there is nothing you can do about it. Keywords such as private, protected or public are simply not allowed in a ClassDeclaration.

And there’s more, there are no getters and setters either. It’s not that writing getters and setters is impossible, it’s just not the way things are done. Everything is rolled into a single method, with a name starting with parm. Sometimes they’re called property methods or parm-methods.

A typical example looks like this:

CustAccount parmCustAccount(CustAccount _custAccount = custAccount)
    custAccount = _custAccount;
    return custAccount;

It may look confusing but it is actually quite simple. If you use it as a setter, the new value is passed to the object’s data member (custAccount) and the return value is never used. When used as a getter, _custAccount gets the current data member as a default value and this value is eventually returned.

The important thing is that you can use it just like getters and setters you might know. Instead of getCustAccount(), use parmCustAccount(). Instead of setCustAccount(‘1234’), use parmCustAccount(‘1234’).

I recommend you do it this way for any new classes you create. This is something I need to point out in code reviews with new X++ developers all the time. You could argue that the function does two things and in theory it should only do one thing. That’s true. However, this is a minor offense that will not make or break your application. Adhering to the existing code style is important too. Being consistent improves overall readability and usability of the code. When in Rome do as the Romans do.

A quick tip for enums

When you’re creating a new base enum consider using multiples of 10 for values. This makes extending enums a lot easier, especially if it indicates some kind of status. Those of you who once programmed in BASIC, or any other language with line numbers, can probably guess where I’m going with this. My apologies for any painful flashbacks this may trigger.

Suppose you’re creating an interface with another system. It turns out you need a new enum, MessageStatus. Values are assigned automatically, so Received = 0, Started = 1, Processed = 2, and Archived = 3.

Of course, at some point you need to do different things depending on the status. Let’s say you have written this function.

boolean isOpen(MessageStatus _status)
    return _status < MessageStatus::Processed;

This is a simple way to indicate at which point the message is no longer considered open. Standard Dynamics Ax contains similar examples, e.g. with the inventory status (StatusIssue and StatusReceipt).

Your message handling system goes live and works perfectly. Users are happy, birds are singing, the sun is shining.

After a while users decide they need a verification step before moving to Started. You extend the enum and end up with MessageStatus::Verified = 4. And now things are broken. Verified messages aren’t handled correctly.

You need to check all places where the status is used. You run across the isOpen() method and change it.

boolean isOpen(MessageStatus _status)
    return _status < MessageStatus::Processed || _status == MessageStatus::Verified;

Not so readable anymore but it works. For now. Things can get out of hand quickly if more than 1 status is added.

This could have been avoided from the start if the enum elements were assigned specific values.

Received 10
Started 20
Processed 30
Archived 40

Adding a new step somewhere in the middle is easy. Create Verified with value 15 and isOpen() doesn’t need to be modified.

Now you may think this is a great idea (It is. Thank you.) but don’t go changing all your enums now. Changing values means you also need to modify all fields that use it, as they still contain the old numbers. This is the reason you need to think about enum values in advance. Once a system is deployed, it’s usually better to leave these things as they are to avoid even more trouble.

In practice starting with multiples of 10 is enough to deal with any reasonable modifications. I have yet to run into a situation where a gap of 9 values isn’t enough. Unfortunately standard Dynamics Ax enums have continuous values starting at 0. If you need to insert something in between you still have to check all code that covers a range of enum elements.

Inventory marking issue in Axapta 3.0

There’s a problem when modifying marked transactions. It’s possible to end up with a transaction that is not reserved but has a reference lot ID anyway, i.e. is marked to another transaction. This can lead to hard to explain problems down the line, e.g. after running the master planning planned orders are missing or incorrectly matched to outgoing transactions.


There is an easy way to trigger this. Create a sales order for an item. Then create a linked purchase order for the amount sold. This marks both inventory transactions to each other. The inventory transaction for the sales line issue is in status reserved ordered and contains the reference lot ID of the purchase order line.

Now increase the quantity on the sales line. This creates a second inventory transaction for the new quantity in issue status on order and with the same reference lot ID. This means the new quantity is also marked to the same purchase order. This is obviously not correct.

Marking implies reserved transactions (physically or ordered) and the quantities on both sides should match. In this case the purchase order is not sufficient for the quantity sold. That’s why the new transaction is put in status on order in the first place. Unfortunately the marking is not fixed.

Something similar happens when you increase the purchase quantity instead of the sales quantity.


This behavior is fixed in Dynamics Ax 4.0 SP1. And the good news is it can be backported. The bug resides in InventUpd_Estimated.createEstimatedInventTrans(). This is where a new InventTrans record is created for the added quantity. It correctly determines the issue status and then stops. In 4.0 the marking is checked there as well.

The end of the method looks like this:

if (movement_Orig)
updEstimated += qty;

Replace it with this:

updEstimated += qty;
// Fix 4.0 SP1 >>
if (movement.inventRefTransId()) // Marking for entire lotId exists => additional should also be marked
    markNow = InventTrans::updateMarking(movement.inventRefTransId(), movement.transId(), -qty,  '', SortOrder::Descending);
    if (markNow)
        if(abs(markNow)  0 ? abs(markNow) : - abs(markNow));
        inventTrans.InventRefTransId =  movement.inventRefTransId();
        InventTrans::findTransId(inventTrans.InventRefTransId, true).updateSumUp();
    if (qty < 0) // issue
        InventUpd_Reservation::updateReserveRefTransId(movement);   // try to make reservation according to marking -
        inventTransMovement = InventTrans::findTransId(movement.inventRefTransId());
            movementIssue = inventTransMovement.inventMovement(true);  // no Throw if not initiated
                InventUpd_Reservation::updateReserveRefTransId(movementIssue);  // try to make reservation according to marking -
    if (!markNow &amp;&amp; inventTrans.InventRefTransId) // reset InventRefTransId if no marking could be made
        inventTrans.InventRefTransId = &#039;&#039;;
// <<
if (movement_Orig)

You’ll also need to add these variables at the top:

InventQty           markNow;
InventMovement      movementIssue;
InventTrans         inventTransMovement;

Final remarks

I could reproduce this on a standard 3.0 SP5 installation. I was a bit surprised to see that this has gone unnoticed for so long. However it is a subtle bug that is hard to spot. The transaction status is correct and the effects of marking aren’t immediately visible.

This kind of inconsistency can really mess up the InventTrans table. Without the fix try, increasing the purchase quantity and then on the sales order remove the inventory marking completely. You end up with several inventory transactions for the purchase order. Some of which are still marked to the sales order.