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:

        timer.start(1);
        for (i=1; i<=maxLoop; ++i)
        {
            // method call here
        }
        timer.stop(1);

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
6SysDictClass3,095
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.

Conclusion

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.

A glimpse of version control options for Ax 5.0

Michael Fruergaard Pontoppidan created a screencast about the version control options for the next major Ax release. In addition to Visual Sourcesafe, Ax will also support Team Foundation Server and a new source control system in Ax itself.

It looks promising but so was the prospect of Sourcesafe integration for 4.0. Unfortunately it turned out to be only marginally usable. The requirement to have a complete database and AOS setup per developer makes it hard to handle multiple projects or do development at the customer’s site.

The video seems to acknowledge this. Sourcesafe and TFS are clearly positioned as tools for ISVs that make modules. Developing modules is different than doing a customer specific implementation and can more easily incorporate VSS or TFS as part of their toolbox. Although I’m skeptical about this, I really hope the new Morphx VCS will provide a decent source control solution for all of us. Ax needs more tools like that to make good development practices less cumbersome.

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(
                            prodTable.BOMId,
                            prodTable.BOMDate,
                            prodTable.ItemId,
                            prodTable.inventDim().ConfigId,
                            false);
    ;
    BOMSearch.init();
 
    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.

10 tips for debugging in Dynamics Ax

Fixing bugs requires quite a bit of experience and knowledge of the modules involved, both on a technical and functional level. The first step to fix something is to find the cause of the problem, a.k.a. debugging.

You shouldn’t limit yourself to using the debugger when things go wrong. Debugging can help you understand the system. I often fire up the debugger just to see what happens in a standard application. This helps me to see how modifications can be implemented and what the consequences are. Dynamics is too big and too complex to be able to just dive in and change something.

Here are some tips to help you in the fine art of debugging. Some might be blatantly obvious to experienced developers. These are things I wish I had known when I first started working with Axapta.

Assume you broke it
This is probably the most important advice. We developers tend to think we write good code. Some of us do, some of us don’t. But nobody does it flawlessly. By default, assume anything you didn’t write yourself works perfectly. This narrows down the search considerably. After careful debugging you may come to a different conclusion. In which case you’ll have a good bug report to file.

If a system has been running fine for a while and it suddenly breaks down after importing new code, those changes are likely to be the root cause of the problem. Try reverting your changes and doing the exact same thing. If the problem remains, you have found an unrelated problem. If not, you know where to start looking for errors.

Get a clear description of the problem
Unless the error is clear enough and you immediately know how to fix it, you’ll need a detailed description how to trigger this error. Unfortunately this can be very hard. Getting users to tell you exactly what you need to understand a bug isn’t that simple. Keep in mind that users are generally not interested in the program they’re using. They just want to get their job done. They have been taught to use the system in a certain way and unexpected errors confuse them. They might not realize what’s different when things go wrong compared to when everything just works.

You need to ask the right questions. If necessary sit next to them and watch them work. Take notes and try to notice special cases. And don’t forget to ask what the correct behaviour should be. There may be no error message and whatever happens may look correct but the user could be expecting a different result.

Without a good scenario it may be impossible to solve some bugs.

Don’t worry to much about errors that only occur once
If something goes wrong only once and it doesn’t happen again, don’t worry too much about it. Depending on the risk it may be better to fix the damage and move on. There’s probably a bug lurking somewhere but you have to decide if it’s worth chasing it.

Intercept error messages
Anything sent to the info log window passes through the add() method on the Info class. Put a breakpoint there if you want to know where a message is triggered. Using the stack trace in the debugger it’s usually not that hard to see which conditions cause it.

Often it turns out to be a missing setting in one of the basic tables.

Intercept data modifications
Not all bugs come with an easy to intercept error message. Sometimes all you get is bad data. It’s possible to see when and why records are created, modified or deleted by putting breakpoints in insert(), update() or delete() on a table. Create them if necessary. Just being able to look at the stack in the debugger when these are called can be very insightful.

Remember that it is possible to modify data without passing through these methods. Like using doInsert(), doUpdate() or doDelete(), or using direct SQL. It’s not very common but sometimes you can miss something.

Intercept queries
If you suspect a query is not correct you’ll want to verify its output. A way that doesn’t require much work is using the postLoad() method. It can be overridden on each table and is called for each selected record. It even works with complex joins. Putting an info() in the postLoad() of each table in a query can tell you a lot about what’s happening.

The cross-reference is your friend
The cross-reference is one of the most important tools when developing and debugging in Dynamics Ax. Always try to have an environment somewhere with an updated cross-reference (not the live environment). You can find the cross-reference in the development tools menu.

Need to know where a field gets its value? The cross-reference tells you where every read and write happens.
Want to know where an error message is used? Open the label editor and find the label, then click the Used By button.

Set up a separate environment
When dealing with complex problems it helps to have a separate environment for debugging. This allows you to freely modify code and data without affecting the live system. This is very important when you have to post invoices or do anything else that is basically irreversible.

It also prevents live users from being blocked if you have breakpoints in the middle of a transaction.

Dealing with large datasets
Sometimes a problem can only be reproduced in (a copy of) the live environment. You’re often stuck with a lot of data that doesn’t matter but gets in the way. Like when you need to debug the MRP. Using regular breakpoints doesn’t help because it takes too long before you get to the real issue.

In this case you need to have some more tricks up your sleeve to narrow down the search. One option is to work in several passes. Using the cross-reference determine places where something interesting happens and dump data with info() or Debug::printDebug(). This should narrow down the possible suspects. With a bit of luck just looking at the data can be enough to identify the problem.

Another way is implementing your own conditional breakpoints. The debugger doesn’t offer these out of the box but you can roll your own with an if-statement and the breakpoint statement. This is very effective if you have some more or less unique identifier of the problem, like a record ID or a customer account or even a date.

Clean up
Don’t forget to remove any modifications you made while debugging. You probably don’t want to leave a hardcoded breakpoint in a live system. Been there, done that, very annoying.

Good luck hunting for bugs.

Feel free to share your debugging techniques.

Reflection with the Dictionary

In X++ it is possible to write code that inspects the structure of other X++ code. This is sometimes called reflection or meta-programming.

You may wonder why you’d want to do that. Reflection is a very powerful tool and opens a wide array of possibilities. Without it some things would be very hard or even impossible to implement. Just look at the code behind table browser, the unit testing framework, or the data export and import tools.

There are several ways to do reflection in X++. I’m going to show an example using the Dictionary. It involves classes whose names start with Dict and SysDict. The latter are subclasses of their respective Dict-class and can be found in the AOT.

The goal

Suppose you need to analyze the performance of an existing application. You could set up monitoring but you need an indication where to start. The largest tables in the database, i.e. those with most records, are potential performance bottlenecks. For large tables it is important to have the right indexes that match the usage pattern of the customer. We’re going to make a simple tool to find those tables. You could also check if new tables from customizations have indexes and so on.

Getting started

First we need to get a list of tables in the application. The kernel class Dictionary has the information we need. It tells us which classes, tables and other objects are defined in the application. To iterate over the list of tables we can use something like this:


static void findLargeTables(Args _args)
{
    Dictionary      dictionary;
    TableId         tableId;
    ;

    dictionary = new Dictionary();

    tableId = dictionary.tableNext(0);

    while (tableId)
    {
        info(int2str(tableId));

        tableId = dictionary.tableNext(tableId);
    }
}

The tableNext() method gives the ID of the table following the given ID. So we start with the non-existant table ID 0 and get back the first table in the system. For now we’ll just print the result to the infolog.

Weeding out the junk

If you scroll through the infolog you’ll notice it also includes things we aren’t interested in, such as temporary tables, (hidden) system tables, views, and table maps. We need to skip these.

Enter the SysDictTable class. Whenever possible you should use the SysDict version of any class in the Dictionary API because they contain very useful additional methods. You’ll see an example in a minute.


static void findLargeTables(Args _args)
{
    Dictionary      dictionary;
    TableId         tableId;

    SysDictTable    dictTable;
    ;

    dictionary = new Dictionary();

    tableId = dictionary.tableNext(0);

    while (tableId)
    {  
        dictTable = new SysDictTable(tableId);

        if (!dictTable.isMap() && !dictTable.isView() &&
            !dictTable.isSystemTable() && dictTable.dataPrCompany())
        {
            info(strFmt('%1 - %2', tableId, tableId2Name(tableId)));
        }

        tableId = dictionary.tableNext(tableId);
    }
}

Some methods tell us what kind of table we’re dealing with and any special case is ignored. For this example I’m only interested in a single company.

Counting

Now need to know which tables have the most records. SysDictTable can count the records for us. To keep track of the results we’ll use an array. The index indicates the number of records and the value is a container of table names. This is a simple data structure that doesn’t require any new tables or classes. The results are ordered and it can deal with several tables having the same record count. The only catch is we need to keep in mind that not all array indexes will have a value.

It’s easier than it sounds. First we take out the info() in the loop and put in some real logic.


        if (!dictTable.isMap() && !dictTable.isView() &&
            !dictTable.isSystemTable() && dictTable.dataPrCompany())
        {
            currCount = dictTable.recordCount();
            if (currCount > 0)
            {
                if (recordCounts.exists(currCount))
                {
                    tables  = recordCounts.value(currCount);
                    tables += dictTable.name();
                }
                else
                {
                    tables = [dictTable.name()];
                }

                recordCounts.value(currCount, tables);
            }
        }

We ignore empty tables and then check if we need to add our table to an existing container or create a new one.

After inspecting the tables we can print the top 10.


    printed = 0;
    i = recordCounts.lastIndex();
    while (i > 0 && printed  0 )
    {
        if (recordCounts.exists(i)
          && conLen(recordCounts.value(i)) > 0)
        {
            info(strFmt("%1 - %2", i, con2str(recordCounts.value(i))));
            ++printed;
        }
        --i;
    }

What’s next?

To make it more useful you could add more checks. I included some of these in the XPO.

  • cacheLookup() : to check if a good cache level is set.
  • indexCnt(), clusterIndex() and primaryIndex() : if you want to know if the table has indexes. For large tables a good set of indexes can make a big difference.
  • tableGroup() : for filtering out transaction tables, which are often the ones that need most tuning. Or to find all those Miscellaneous tables that should be in another group.
  • fieldCnt() : counts the number of fields. Tables with a lot of fields take up more space and require more round trips between AOS and database when fetching data. So don’t go overboard when adding new fields. It’s a good idea to check the field count every now and then when developing.
  • recordSize() : tells you how big a single record is in bytes. This depends on the number of fields and the data types.

There’s a lot more you can do with the Dictionary classes. To get an idea of the possibilities you can check how dictionary classes are used in the standard application.

In later posts I’ll give more examples how to read (and modify) the AOT structure in X++.
XPO for Dynamics Ax 4.0.

Table browser with field groups

The table browser is a great tool but it can be hard to find the fields you’re looking for in the grid. Standard Ax either shows all fields or the fields in the AutoReport field group.

Sometimes I like to use another field group so I added that option to the table browser. Now I can use any field group defined on the table. Filtering out the irrelevant fields makes browsing the data a lot easier.

Table browser screenshot

It wasn’t too hard to implement. Standard Ax code can already handle any field group but there is no way to choose one. On the form SysTableBrowser I replaced the radio button with a combobox and then modified the class SysTableBrowser to use that instead of the radio button.

XPO for Dynamics Ax 4.0