Monday, July 13, 2020

X++ Performance optimization

Many of us struggle to deal with system performance for such operation where huge data interactions are involved. You might have some business process, which need to complete within certain business hours due to dependency of a particular process with others.
Let’s see what are the key considerable points while doing performance optimization
1.       Identify the issue :
a.       SQL activity MONITOR: SQL activity monitor is the great tool on Sql management studio which you can see what kind of operation is running on SQL , how is the query executing and is there any blocking statement. Tabs inside the view provide can be used to see sql statements

                Here you have to focus mainly on below areas
·         Expensive query: This tab will show you the expensive queries which is hitting system’s performance, you have to optimize your select statement accordingly
·         Blockers : In processing tab, you can filter the queries by block which give you the list of all those statement which is blocker and cause of performance issue

 
LCS system DIAGNOSTICS and monitoring: for multitier environment , we have to use lcs system diagnostics option available under LCS>environment> Monitoring> Diagnostics> environment monitoring. In this page you can find the blocking statement or expensive queries under ‘SQL insights’ tab


2.       Possible areas to help on performance improvement
a.       Indexes and cache lookup : You have to make sure that tables you are using in your operation having proper indexes and cache lookup, many of us are aware about indexing but people take table’s cache lookup property lightly but in actual it play the key role while fetching data. You can follow below rule by referring your table type
Table Group
Cache Lookup
Miscellaneous*
 See notes below
 Parameter
 EntireTable
 Group
 Found
 Main
 Found
 Transaction
 NotInTTS
 WorksheetHeader
 NotInTTS
 WorksheetLine
 NotInTTS
 Framework
 N/A
 Reference
 Found
 Worksheet
 NotInTTS
 TransactionHeader
 NotInTTS
 TransactionLine
 NotInTTS

You have to also make sure that inside your X++ select statement, respective tables are indexed in order you to your where clause

By using this option, you can see the sql execution plan for above expensive query, this will help you to identify if there is any index related option can be done on your used tables


When viewing the execution plans for these queries, you have to keep in mind that every index you need to add to improve read performance has a negative impact on write performance. Before implementing any of these changes, I want to test them and make sure the benefits outweigh the costs.
As you can see on above plan, system is indicating that your table need a non-cluster index on table and you have to refer the same index name in index hint

b.       Temp table: Using temporary table to store some data for a particular process is the good option like a summary report on form level to show calculated data but it affect system performance if you are using it on lengthy operation and trying to fill the data under any loop.
Whenever you use a fresh object of temp table, system perform SQL jobs to flush the data thus be careful by using temp table.
Below are few more details about table type
Regular – a standard physical table.
InMemory – For this kind of table, system keep the data in memory but not in SQL physically. This can be used to perform any kind of calculation like in form if use want to see the summery. You can use this table to keep calculated data to show but if you try to use this table on your lengthy operation will not help much instead you will face performance issue.
TempDB – A new table type introduced in AX, which keep the data in SQL but inside system, runs some SQL store procedure to fill and flush the data, by using this type, you can use your temp table in join operation.
Tip: We know that a tempDB type table keep the data buffer only in variable scope but if you want to use two object for same temp table and need to refer the same data you can use linkPhysicalTableInstance() method as below
{
myTempDBTable             tmpA,tmpB;

tmpA.Field1= value1;
tmpA.Insert();

tmpB.linkPhysicalTableInstance(tmpA);
}
c.       View: if you are using multiple tables in your select statement, you should create a view. This will help to improve executing select statement.
Example: I have to fetch the data from many tables by using complex query as below

select retailDiscountMixAndMatch
                    where   RetailDiscountMixAndMatch.Status== RetailDisabledEnabled::Enabled &&
                            RetailDiscountMixAndMatch.ValidFrom<=_custInvoiceTrans.InvoiceDate &&
                            RetailDiscountMixAndMatch.ValidTo>=_custInvoiceTrans.InvoiceDate &&
                    exists join retailPeriodicDiscountLine
                    exists join retailGroupMemberLine
                    exists join ecoResProduct
                    exists join EcoResProductCategory
                    exists join EcoResCategoryTmp
                    where retailDiscountMixAndMatch.OfferId == retailPeriodicDiscountLine.OfferId
                    && retailPeriodicDiscountLine.RetailGroupMemberLine == retailGroupMemberLine.RecId
                    && (retailGroupMemberLine.Product == ecoResProduct.RecId || (!retailGroupMemberLine.Product && retailGroupMemberLine.Category))
                    && (EcoResCategoryTmp.EcoResCategoryIdBase ==EcoResProductCategory.Category || (retailGroupMemberLine.Product && !retailGroupMemberLine.Category))
                    && (EcoResCategoryTmp.EcoResCategoryIdParent==retailGroupMemberLine.Category || (retailGroupMemberLine.Product && !retailGroupMemberLine.Category))
                    && ecoResProduct.DisplayProductNumber == _custInvoiceTrans.ItemId
                    && (EcoResProductCategory.Product == ecoResProduct.RecId || !EcoResProductCategory.Category)
                    exists join salestable
                    where SalesTable.SalesId == _custInvoiceTrans.OrigSalesId
                    exists join retailChannelTable
                    where SalesTable.DestinationStore == retailChannelTable.RetailChannelId
                    exists  join retailChannelPriceGroup
                    where retailChannelTable.RecId == retailChannelPriceGroup.RetailChannel
                    exists join retailDiscountPriceGroup
                    where retailDiscountPriceGroup.OfferId == retailDiscountMixAndMatch.OfferId
                    && retailChannelPriceGroup.PriceGroup == retailDiscountPriceGroup.PriceDiscGroup

This kind of heavy select statement can be optimized by creating a view like below



Now the above statement can be reduced as below and this will improve query execution

select RetailDiscountMixAndMatchView
            join custInvoiceTransView
            exists join EcoResCategoryTmp
            where custInvoiceTransView.SalesId == custInvoiceJour.SalesId &&
            RetailDiscountMixAndMatchView.ValidFrom <= custInvoiceTransView.InvoiceDate &&
            RetailDiscountMixAndMatchView.ValidTo >= custInvoiceTransView.InvoiceDate &&
            ((custInvoiceTransView.POSOrderType == HS_POSOrderType::DD && RetailDiscountMixAndMatchView.HS_DDAppFullFillment == NoYes::Yes)
            ||
            (custInvoiceTransView.POSOrderType == HS_POSOrderType::DFill && RetailDiscountMixAndMatchView.HS_DFillAppFullfillment == NoYes::Yes)
            ||
            (custInvoiceTransView.POSOrderType == HS_POSOrderType::Instore && RetailDiscountMixAndMatchView.HS_InStoreAppFullfillment == NoYes::Yes)) &&
            (RetailDiscountMixAndMatchView.Product == EcoResCategoryTmp.Product || (!RetailDiscountMixAndMatchView.Product && RetailDiscountMixAndMatchView.Category)) &&
            (EcoResCategoryTmp.EcoResCategoryIdBase ==RetailDiscountMixAndMatchView.Category || EcoResCategoryTmp.EcoResCategoryIdParent==RetailDiscountMixAndMatchView.Category
                || (RetailDiscountMixAndMatchView.Product && !RetailDiscountMixAndMatchView.Category)) &&
            EcoResCategoryTmp.ItemId == custInvoiceTransView.ItemId &&
            EcoResCategoryTmp.BatchHeaderId == batchHeaderId &&
            custInvoiceTransView.HS_DestinationStore == RetailDiscountMixAndMatchView.RetailChannelId;

d.       Inner loops : There are many ways to avoid inner loops, please make sure that you have minimum loops to perform the operation, for example to fetch the data from header and line, use one while select statement instead of two while
e.       Join statement: In any lengthy operation you may be having multiple sub tables with join statement, if you don’t want to fetch the data from sub tables and using them only to filter the data, please use exists join
f.        Index hint: You should use respective cluster index as index hint in your select statement
g.       Locking: Record locking is the one of the key factor of any data operation. If in your operation you are trying to fetch the data and if there is any operation to delete/update record for same table, you will face locking issue. Its very common on multithreading operation. To avoid it, you can maintain a log table or can refer specTrans table where you can add respective record reference. You can perform such delete/update operation at the end of operation

Example : in below example, we can use one update statement instead of updating record in loop to avoid any kind of blocking

While select CustInvoiceJour where CustInvoiceJour.MyFlag=false
{
SpecTrans     specTransTmp;

this.ProcessSomething();

//Need to mark custInvoiceJour is processed
specTransTmp.setTempDB();
specTransTmp.RefRecId = custInvoiceJour.RecId;
specTransTmp.RefTableId =  tableNum(custInvoiceJour);
       specTransTmp.RefCompany = custInvoiceJour.DataAreaId;
specTransTmp.insert();
}

//Finally
update_recordset custInvoiceJour setting MyFlag =true
            join specTransTmp
            where specTransTmp.RefRecId ==custInvoiceJour.RecId
            && specTransTmp.RefTableId == custInvoiceJour.TableId;

h.       Multithreading : For any bulk data operation, multithread is the only one option where you can run many task simultaneously to complete the operation in a time frame