abap perofrmance tuning

26
1 Declaration: I here by declare that this document is based on my personal experiences. To the best of my knowledge, this document does not contain any material that infringes the copyrights of any other individual or organization including the customers of Infosys. (Vemuru Vinod Kumar) Target readers: All ABAPers. Introduction: SAP R/3 is the most successful product for enterprise resource planning (ERP). It is being used by many companies and had many modules to cover end to end business of most of the companies including human resource management (HR). SAP R/3 is based on a relational database management system (RDBMS) which is used to store all R/3 related and application data. E.g. Company’s sales and marketing information, Historical data etc Very good performance is crucial for the users of SAP R/3 system and is expected from every individual. It is a general requirement to process various transactions concurrently for thousands of users by SAP R/3 and the underlying database system. In addition, the size of the database system will tend to grow day by day in tune with business growth of the company. As a result the performance of the system will tend to go down, which is not expected from customer point of view. Unfortunately, tuning the performance of an SAP R/3 system is very difficult because both the R/3 application system and the underlying database system must be tuned which is not feasible in reality. Furthermore, the performance of an R/3 system can be impacted because parts of R/3 system were designed and implemented in the early eighties at a time when commercial database systems were immature. Finally, SAP R/3 is an open system that allows customers and third-party vendors to integrate specialized modules which are not part of the Standard R/3 system. Such modules can severely impact the performance of the whole SAP system. By taking care of proper design of ABAP applications we can address performance issues at least to some extent. This document describes the Performance improvement methodologies and standards that can be followed in ABAP coding to improve the performance of the ABAP objects. Performance tuning in ABAP

Upload: sagar-ranasingh

Post on 19-Jan-2016

45 views

Category:

Documents


1 download

DESCRIPTION

Various Ways to enhance ABAP code to optimize Performance

TRANSCRIPT

Page 1: ABAP Perofrmance Tuning

1

Declaration:

I here by declare that this document is based on my personal experiences. To the best of my knowledge, this document does not contain any material that infringes the copyrights of any other individual or organization including the customers of Infosys.

(Vemuru Vinod Kumar)

Target readers: All ABAPers.

Introduction:

SAP R/3 is the most successful product for enterprise resource planning (ERP). It is being used by many companies and had many modules to cover end to end business of most of the companies including human resource management (HR). SAP R/3 is based on a relational database management system (RDBMS) which is used to store all R/3 related and application data.

E.g. Company’s sales and marketing information, Historical data etc

Very good performance is crucial for the users of SAP R/3 system and is expected from every individual. It is a general requirement to process various transactions concurrently for thousands of users by SAP R/3 and the underlying database system. In addition, the size of the database system will tend to grow day by day in tune with business growth of the company. As a result the performance of the system will tend to go down, which is not expected from customer point of view. Unfortunately, tuning the performance of an SAP R/3 system is very difficult because both the R/3 application system and the underlying database system must be tuned which is not feasible in reality. Furthermore, the performance of an R/3 system can be impacted because parts of R/3 system were designed and implemented in the early eighties at a time when commercial database systems were immature. Finally, SAP R/3 is an open system that allows customers and third-party vendors to integrate specialized modules which are not part of the Standard R/3 system. Such modules can severely impact the performance of the whole SAP system. By taking care of proper design of ABAP applications we can address performance issues at least to some extent.

This document describes the Performance improvement methodologies and standards that can be followed in ABAP coding to improve the performance of the ABAP objects.

1. Selection screen validations:

Selection screen validation is a common requirement in almost all the reports. Points to be remembered while doing selection screen validations.

1. First check whether the selection screen field (Select option/Parameter) has some value or not before hitting the data base for validating. It is meaning less to do validation for a blank value.

Performance tuning in ABAP

Page 2: ABAP Perofrmance Tuning

2

2. It’s a common practice to use SELECT SINGLE * for selection screen validations. It is needless to select all the table fields when we are interested to validate a single field. It is advisable to select only the required field instead of SELECT SINGLE *.

3. Always check for the validation against CHECK table. Even though we check for validation in some other linked table, internally a check happens against the check table i.e Linked table entry will be created with reference to Check table. Also there is no chance of duplicates in check table as the check field(s) will be the primary key. This improves the performance to a great extent.

EG: SELECT-OPTIONS: so_vkorg FOR vbak-vkorg.DATA: wa_vbak TYPE vbak, w_vkorg TYPE tvko-vkorg.

Don’t do:AT SELECTION SCREEN OUTPUT.SELECT SINGLE * INTO wa_vbak FROM vbak WHERE vkorg IN so_vkorg.IF NOT sy-sybrc IS INITIAL.

MESSAGE e100.ENDIF.

Do:AT SELECTION-SCREEN ON so_vkorg.CHECK NOT so_vkorg[] IS INITIAl.

PERFORM validate_vkorg.CHECK NOT sy-sybrc IS INITIAL.MESSAGE e100.

FORM validate_vkorg. DATA: l_vkorg TYPE tvko-vkorg. SELECT SINGLE vkorg INTO l_vkorg FROM tvko WHERE vkorg IN so_vkorg.ENDFORM.

NOTE: Check table for sales org. is TVKO. (We can check this in SE11)

2. Select Statement:

Select is the basic statement of any Report. This is one of the most important areas where we generally get performance issues. We will look in to this in depth by considering various factors which cause performance issues in select statements.

2.1SELECT CLAUSE:

It is always advisable to select only the required fields instead of simply using SELECT *. This will reduce the transportation cost to a great extent. This is because of time involved in transferring data of each field from data base server to application server. If we specify SELECT * then it will transfer all the fields which is not advisable unless it is really required. For this we need to specify field list of the required fields in the select clause. Another

Page 3: ABAP Perofrmance Tuning

3

important point to remember is the order of the fields in the field list should be same as they appear in data base table.

If you want to avoid duplicates then simply select all the key fields plus the required fields. In this case we need not use DELETE ADJACENT DUPICATES. If the duplication check is based on fields other than key fields then we have to DELETE records explicitly by comparing those fields.

If you are sure that you get a single record then use addition SELECT SINGLE.

2.2INTO CLAUSE:

Always the structure specified in the INTO clause should be same as the field list specified in SELECT clause. If we have more fields in field list than the number of fields in the structure of into clause or field types mismatching then a runtime error occurs. If the field list is less than the number of fields in the structure of into clause, then the fields are placed from left to right. So the extra right most fields will have their initial values. Again if there is any field type mismatch then run time error occurs.

Always the field types of the structure in the INTO clause should match with that of the source fields (Data base fields) from where we fetch the data. This will avoid run time conversion costs.

Avoid using INTO CORROSPONDING FIELDS addition. It involves additional cost for placing the data into corresponding fields of the structure.

Use INTO TABLE i_itab. We will get data into internal table in a single operation.

2.3FROM CLAUSE:

This is the place where we can specify Tables, Views and Joins and whether to read data directly from data base or from Buffer.

The SAP database interface enables storage of database tables in local buffers, i.e. the buffers reside locally on each application server of the system. Buffering is especially important in a client/server environment because the access time using the network is much greater than the access time to a locally buffered table.

So never use BYPASSING BUFFER addition unless and until it is really required to select data directly from data base.

Don’t use joins for more than 2 tables. As the number of join tables increases, the efficiency of the join will be reduced. (Logarithmically) Also JOIN has peculiar property. It automatically bypasses buffer. This further reduces the performance of the select by increasing the database load.

2.4WHERE CLAUSE:

Page 4: ABAP Perofrmance Tuning

4

This is the most important part of the select where we can concentrate more to improve the performance. Before writing conditions in WHERE clause first thing we need to check is INDEX of the database table. If any secondary INDEX already exists and the where clause conditions match with the INDEX then specify the condition in where clause in the same order as they appear in the INDEX. If no INDEX exists then specify the fields in the same order as they appear in the data base table.

The order of the fields in the where clause greatly affects the performance. Accessing data base by using INDEX is very much faster because index has the address of the matching record. So the cursor directly goes and fetches those records instead of searching for the records in the whole data base.

We encountered this example in one of our reports. When using JOINS, specify the where clause conditions in the same order of the TABLES in the JOIN and it is advisable to have header table as first JOIN table. This again depends on requirement. Just look at the example below.

CASE1:

SELECT a~vbeln a~fkart a~vbtyp a~vkorg a~zuonr b~posnr b~meins b~fklmg b~ntgew b~gewei b~matnr b~vkbur b~erdat INTO TABLE i_vbrp FROM vbrk AS a INNER JOIN vbrp AS b ON a~vbeln EQ b~vbeln WHERE a~vbtyp NE lc_n AND a~vbtyp NE lc_o AND b~erdat IN r_erdat AND b~aland EQ c_aland.

CASE2:SELECT a~vbeln a~fkart a~vbtyp a~vkorg a~erdat

a~zuonr b~posnr b~meins b~fklmg b~ntgew b~gewei b~matnr b~vkbur

INTO TABLE i_vbrp FROM vbrk AS a INNER JOIN vbrp AS b ON a~vbeln EQ b~vbeln WHERE a~vbtyp NE lc_n AND a~vbtyp NE lc_o AND a~erdat IN r_erdat AND b~aland EQ c_aland.

Here we can give the ERDAT condition both from VBRK and VBRP. But if we see the order of table in the JOIN, VBRK comes first. After changing this single condition we got surprising performance improvement of 3X.

Specify as many key fields as we can in the where clause. This is the point where performance of select query depends.

Page 5: ABAP Perofrmance Tuning

5

I read this logic in some forum. I tried implementing this. Results are impressive for some of the selects. It reduced the runtime of select query slightly.

If we can’t pass all the key fields then instead of not giving any thing in the where clause we can implement this. Declare some constants of same type of the key fields which we can’t pass and INITIALIZE to their INITIAL values. Now use these variables in WHERE clause by using GE comparison operator. Just look at the following example.

CONSTANTS: c_vbeln TYPE vbfa-vbeln VALUE IS INITIAL, c_posnn TYPE vbfa-posnn VALUE IS INITIAL, c_vbtyp_n TYPE vbfa-vbtyp_n VALUE IS INITIAL,

CASE1:

SELECT vbelv posnv vbeln posnn vbtyp_n rfmng meins INTO TABLE i_vbfa FROM vbfa WHERE vbelv IN so_vbeln AND posnv IN so_posnv.

CASE2:

SELECT vbelv posnv vbeln posnn vbtyp_n rfmng meins INTO TABLE i_vbfa FROM vbfa WHERE vbelv IN so_vbeln AND posnv IN so_posnv AND vbeln GE c_vbeln AND posnn GE c_posnn

AND vbtyp_n GE c_vbtyp_n.

This will definitely improve the performance to a considerable extent.

Last but the most important point is “First primary key of the table should always exist in the where clause of the select query”. This thing we can simply check by executing any table having more than one primary key field. If we are able to provide first primary key then the select will be very fast. This again depends on business requirements. In some of the cases we can’t provide the first primary key. In this case at least try to provide second primary key.

Another technique is if we have non primary keys in where clause then first select the data based on primary keys and later delete the internal table records which doesn’t satisfy non primary key conditions. This technique will also improve performance to some extent.

2.5 FOR ALL ENTRIES:

SELECT… ENDSELECT or NESTED SELECTS can be effectively replaced with the usage of FOR ALL ENTRIES. In case of SELECT ENDSELECT the data base will be fired equal to the number of entries fetched which increases the network traffic to a great extent and hence degrades the performance of not only your object but also other objects which are accessing

Page 6: ABAP Perofrmance Tuning

6

the same data base. The best solution for this is to get the data in a single fetch. This can be done by using FOR ALL ENTRIES addition in SELECT.

This will also work in the same way as SELECT ENDSELECT but we will get all the records in a single fetch. Although it is advisable to use this we should do some mandatory checks before using this. Some of these are

1. CHECK whether the driver table is INITIAL or NOT.(Mandatory)2. SORT the Driver table based on the fields to be specified in WHERE CLAUSE. (To

Improve performance)3. DELETE ADJACENT DUPLICATES FROM the Driver table. (To Improve performance)

Draw backs: Although it’s very good to use this, still there are a few drawbacks.

1. If we don’t check the Driver table is INITIAL or NOT and if it is INITIAL then the select will fetch all the entries in data base which is an unexpected result.

2. Field type and length of Driver table and driven table must match in the WHERE clause. Otherwise program throws a syntax error. Some times for this requirement we need to take some extra internal table.

3. FOR ALL ENTRIES automatically deletes duplicate records. To avoid this we have select all the key fields even if we are not going to use them.

3.6ORDER BY or Explicit SORT?

Just look at the following results of the test program I have created. These results are the average of 10 test runs for each set of number of records.

TABLES: mara.SELECT-OPTIONS: so_matnr FOR mara-matnr.DATA: w_matnr TYPE mara-matnr, w_time1 TYPE p DECIMALS 2, w_time2 TYPE p DECIMALS 2, w_time3 TYPE p DECIMALS 2, w_lines TYPE i, * i_mara TYPE SORTED TABLE OF mara WITH UNIQUE KEY matnr. i_mara TYPE STANDARD TABLE OF mara.

*Order byGET RUN TIME FIELD w_time1.SELECT * INTO TABLE i_mara

FROM mara WHERE matnr IN so_matnr ORDER BY MATNR.

GET RUN TIME FIELD w_time2.w_time3 = ( w_time2 - w_time1 ) / 10000.WRITE: 'By using Order by:', w_time3.*SortCLEAR: w_time1, w_time2, w_time3.REFRESH i_mara[].GET RUN TIME FIELD w_time1.SELECT * INTO TABLE i_mara

Page 7: ABAP Perofrmance Tuning

7

FROM mara WHERE matnr IN so_matnr.

SORT i_mara BY matnr.GET RUN TIME FIELD w_time2.

w_time3 = ( w_time2 - w_time1 ) / 10000.WRITE: /'By using Sort:', w_time3.CLEAR w_lines.

DESCRIBE TABLE i_mara LINES w_lines.WRITE:/ 'No. of records', w_lines.

Results for i_mara TYPE STANDARD TABLE OF mara:

No. of records fetched

Internal table type

Run TimeOrder BY SORT

26 STANDARD .64 1.286 STANDARD 1.5 2.84000 STANDARD 50.5 102.316666 STANDARD 997.64 2773.3217840 STANDARD 3194.2 5764.7291625 STANDARD 11175.75 21090.25

Results for i_mara TYPE SORTED TABLE OF mara WITH UNIQUE KEY matnr:

Page 8: ABAP Perofrmance Tuning

8

Draw backs of Order by: If we specify order by clause in the select then sorting is done in Data base server. This affects other users who access database at that time. In contrary to Order by if we use explicit SORT then sorting will be done on application server which affects only a few users. So it is advisable to use explicit sort. Also as the number of records in the data base increase both take almost same time. So it is better to select the data and then explicitly SORT.

Never ever use SELECT f1 f2…….fn.. END SELECT. Select all the data in a single fetch, store it in an internal table and later process that as per your requirement. Frequent triggering of data base not only affects your program execution time but also affects other users who concurrently access the same data base which is quite common scenario in production. This is because data base access works on queuing principles.

3. LOOPS:

Once data is collected from various database tables into internal tables we have to process the data as per the business requirements. To meet this requirement we often

No. of records fetched

Internal table type Run TimeOrder BY without Order by

26 SORTED TABLE 1.08 2.0486 SORTED TABLE 1.48 2.804000 SORTED TABLE 441.2 102416666 SORTED TABLE 817.5 5568.3617840 SORTED TABLE 888.4 7569.791625 SORTED TABLE 101553.4 105955.3

Page 9: ABAP Perofrmance Tuning

9

use loops. Loop is nothing but reading/processing the data record by record. If we have huge volume of data then program performance goes further down in addition to the time eaten by select statements. Proper design of the program logic will enhance the performance to a great extent.

Always try to avoid nested loops unless there is no way to achieve the requirement. Few techniques to improve the performance of Loops are as below.

1. LOOP AT WHERE or LOOP with CHECK statement?

We often confuse between Loop at Where clause or Loop with check statement. As per my analysis it depends on number of matching records. If the number of matches are less then both tends to takes almost same time. But as the number of matching records increases Loop with check is giving better performance. Check below test results.

With Check statement ( Milli seconds )

With Where clause ( Milli seconds )

Number of matches

Total records in internal table

530.6 557.8 1000 134,2422,566 2,766 5000 134,2425122 5521 10000 134,24226581 28669 50000 134,24239619 42972 75000 134,24252642 57627 100000 134,24257669 64530 133,891 134,242

2. Parallel cursor technique:

Page 10: ABAP Perofrmance Tuning

10

Nested loops are one of the fear factors for all the ABAPers as this also has major share of program execution time. If the number of entries in the nested internal tables is huge, then the situation would be still worse. Although it is advisable that not to use nested loops, it is not possible to completely avoid nested loops because of business requirements. In these cases we have to look at alternative ways of improving performance. One of the solutions for this is to using parallel cursor method whenever there is a need for nested loop. Check below sample code which is self explanatory and of course the amazing results.

REPORT zvinu.TABLES: vbak.

SELECT-OPTIONS: so_vbeln FOR vbak-vbeln, so_erdat FOR vbak-erdat.PARAMETERS: po_rows TYPE i.TYPES: BEGIN OF t_vbak, vbeln TYPE vbak-vbeln, erdat TYPE vbak-erdat, END OF t_vbak,

BEGIN OF t_vbap, vbeln TYPE vbap-vbeln, posnr TYPE vbap-posnr, END OF t_vbap.

DATA: i_vbak TYPE STANDARD TABLE OF t_vbak, i_vbap TYPE STANDARD TABLE OF t_vbap, wa_vbak TYPE t_vbak, wa_vbap TYPE t_vbap, w_time1 TYPE i, w_time2 TYPE i, w_time3 TYPE i, w_count TYPE i, w_index TYPE sy-index.

SELECT vbeln erdat UP TO po_rows ROWS INTO TABLE i_vbak FROM vbak WHERE vbeln IN so_vbeln AND erdat IN so_erdat.

WRITE:/1 'Total number of header records', sy-dbcnt.

CHECK NOT i_vbak[] IS INITIAL.SELECT vbeln posnr INTO TABLE i_vbap FROM vbap FOR ALL ENTRIES IN i_vbak WHERE vbeln EQ i_vbak-vbeln.

WRITE:/1 'Total number of item records', sy-dbcnt.SORT: i_vbak BY vbeln, i_vbap BY vbeln.

Page 11: ABAP Perofrmance Tuning

11

DO 10 TIMES. CLEAR: w_time1, w_time2, w_time3, w_count. GET RUN TIME FIELD w_time1.*Loop at where clause LOOP AT i_vbak INTO wa_vbak. LOOP AT i_vbap INTO wa_vbap WHERE vbeln EQ wa_vbak-vbeln.

ENDLOOP. ENDLOOP.

GET RUN TIME FIELD w_time2. w_time3 = w_time2 - w_time1. WRITE: /1 'Time taken for where clause', w_time3, /1 'Number matching records', w_count.

CLEAR: w_time1, w_time2, w_time3, w_count. GET RUN TIME FIELD w_time1. *Parallel cursor technique MOVE 1 TO w_index. LOOP AT i_vbak INTO wa_vbak. LOOP AT i_vbap INTO wa_vbap FROM w_index. IF wa_vbak-vbeln NE wa_vbap-vbeln. w_index = sy-tabix. EXIT. ENDIF. ENDLOOP. ENDLOOP.

GET RUN TIME FIELD w_time2. w_time3 = w_time2 - w_time1. WRITE: /1 'Time taken for parallel processing' , w_time3, /1 'Number matching records', w_count.ENDDO.

Loop at Where clause ( Milli seconds )

Parallel cursor ( Milli

Number of item records

Number of header records

397173 2933 1043 10002024761 27431 5988 50002247365 70211 12,371 100002,308,025 168,577 29,411 25,0002,479,619 227,577 56,893 50,0002,783,004 440,341 86,399 75,0003,484,387 460,655 116,415 100,000

Page 12: ABAP Perofrmance Tuning

12

4. Field Symbols:

Field symbols are one of the most effective ways of modifying internal tables. They improve the performance by 10X to 50X.

These exactly work in the same way as pointers work in “C” language. Following example shows how a field symbol can be used to modify internal table.

CLEAR wa_discounts.LOOP AT i_discounts INTO wa_discounts.

CASE wa_discounts-kschl.WHEN c_zd01.READ TABLE i_postdata INTO wa_postdata WITH KEY

record_id = wa_discounts-record_idfieldname = c_vvd01BINARY SEARCH.IF sy-subrc IS INITIAL.Wa_postdata-value = wa_discounts-vvd02.

MODIFY i_postdata FROM wa_postdata INDEX sy-tabix.

ENDIF.WHEN c_zd02.READ TABLE i_postdata INTO wa_postdata WITH KEY

record_id = wa_discounts-record_idfieldname = c_vvd02BINARY SEARCH.

Page 13: ABAP Perofrmance Tuning

13

IF sy-subrc IS INITIAL.Wa_postdata-value = wa_discounts-vvd02.

MODIFY i_postdata FROM wa_postdata INDEX sy-tabix.

ENDIF.ENDCASE.ENDLOOP.

The same code can be written like this which improved performance by 10X in our case.

FIELD-SYMBOLS: <wa_postdata> TYPE bapi_copa_data.CLEAR wa_discounts.LOOP AT i_discounts INTO wa_discounts.

CASE wa_discounts-kschl.WHEN c_zd01.UNASSIGN <wa_postdata>.READ TABLE i_postdata WITH KEY

record_id = wa_discounts-record_idfieldname = c_vvd01ASSIGNING <wa_postdata>.IF sy-subrc IS INITIAL.

<wa_postdata>-value = wa_discounts-vvd01.ENDIF.

WHEN c_zd02.UNASSIGN <wa_postdata>.READ TABLE i_postdata WITH KEY

record_id = wa_discounts-record_idfieldname = c_vvd02ASSIGNING <wa_postdata>.IF sy-subrc IS INITIAL.

<wa_postdata>-value = wa_discounts-vvd02.ENDIF.

CLEAR wa_discounts.

ENDLOOP.

After assigning value to the field symbol if we change any value the same will be reflected in the internal table. To clear the contents of field symbol use UNASSIGN statement.

Draw back: Need to take extra care because if we unintentionally do some thing in work area the same will be updated in internal table.

5. Read Table:

Points to be taken care while using read table statement:

Page 14: ABAP Perofrmance Tuning

14

1. Always try to use BINARY SEARCH addition in READ TABLE which improves performance to a greater extent. If we don’t use BINARY SEARCH then every time it searches from the beginning of the internal table. Make sure that the table is sorted in the same order of fields specified in WITH KEY addition. . Also BINARY search will work only if we sort the table in ascending order.

2. If you are sure of the position of the record then specify INDEX addition instead of WITH KEY addition.

3. If you are interested in getting values of only some fields then use addition TRANSPORTING field list. This reduces the transportation cost to a great extent.

4. If you want to check only the existence of the entry then use addition TRANSPORTING NO FIELDS.

5. Never ever use READ without BINARY SEARCH on standard and sorted table (Internal table defined with TYPE STANDARD TABLE OF/ TYPE SORTED TABLE OF) if it has more than 10 rows. The reading costs are logarithmic without BINARY SEARCH.

6. If the number of records is less (Around 20) then LINEAR SEARCH (Default search) is faster than BINARY SEARCH.

Below are the results on a sample program. Internal tables are defined with TYPE STANDARD TABLE OF and with explicit work areas.

Without BINARY SEARCH (Milli seconds)

With BINARY SEARCH (Milli seconds)

Number of records

9 10 1087 98 20256 141 50807 289 10016300 1555 50064300 3260 1000735,905 11177 30001599594 18690 50001736657 39006 100002076145 177722 250002435995 255304 500002592793 478096 750002602874 591665 100000

Page 15: ABAP Perofrmance Tuning

15

6. Modify/Delete/Insert/Append/update:

1. Modify:It is a very common requirement to modify the internal tables while doing

logical processing. Some of the points to be remembered while modifying internal table are

1. Always use addition TRANSPORTING f1 f2…fn. When we are interested in modifying only certain fields, then there is no need to transport all the fields of the work area.

2. It is advisable to specify INDEX which is much faster than a Where clause. Where clause always requires full table scan i.e. it checks each entry in the table with where clause conditions. If we are using MODIFY with where clause inside loop then you can assume how hectic it is.EG:MODIFY i_tab FROM wa_tab INDEX sy-tabix TRANSPORTING fld1 fld2.MODIFY i_tab FROM wa_tab TRANSPORTING fld1 fld2.

But by specifying INDEX we can change one entry at a time. Advantage with WHERE clause is, we can change more than one entry with single MODIFY statement.

3. If we are modifying the internal table based on some field in a loop, check the possibility of using AT NEW event.E.g. If we can have duplicate records based on some field and MODIFY is also on the same field then probably we can use AT NEW event. MODIFY the table in AT NEW event with INDEX and WHERE CLAUSE additions.

Page 16: ABAP Perofrmance Tuning

16

2 Delete:This is also one of the important performance barriers. When ever we delete a

record from an internal table the system has to recreate the index for all the entries if the table is of type STANDARD or SORTED table because these tables work on INDEX mechanism. This will be more time consuming if the internal table is of very big size and deletion frequency is high. It is always better to exclude the entries through where clause of select statement. If it is not possible then delete the entries in single operation. Never use DELETE statement inside a loop unless there is no other way to achieve our requirement. Deleting in single step will have index maintenance costs also once and in case of loop it is equal to number of deletions.

Don’t do:

LOOP at i_ekpo INTO wa_ekpo. IF wa_matnr+0(1) EQ lc_m DELETE i_ekpo FROM wa_ekpo INDEX sy-tabix. ENDIF.ENDLOOP.

DO: DELETE i_ekpo WHERE matnr+0(1) EQ lc_m.

Deleting adjacent duplicates:

Never forgot to SORT the table by the same fields that are used in COMPARING clause of DELETE ADJACENT DUPLICATES. If we want to delete duplicates based on key fields (Not with full primary key as we can’t have duplicates for full primary key) then the best way is to select all the key fields in select statement which automatically avoids duplicates.

4. Append:

Append data into internal tables in a single step rather than doing in a loop.

Don’t do:

LOOP AT i_ekko INTO wa_ekko.APPEND wa_ekko TO i_ekko_post.

ENDLOOP.

Do:

APPEND LINES OF i_ekko to i_ekko_post.

Page 17: ABAP Perofrmance Tuning

17

Copying internal tables:

Copying in a single step will be faster than doing it in a loop.

Don’t do:

LOOP AT i_ekko INTO wa_ekko. APPEND wa_ekko TO i_ekko_post.ENDLOOP.

Do:

i_ekko_post[] = i_ekko[].

5. Insert/Update:

Same conditions as discussed above will apply to INSERT and update also. Always insert data into data base table in bulk but not line by line.

Internal table: If the internal table is of type STANDARD TABLE/ SORTED TABLE then it will work on INDEX mechanism.

E.g.: If the table is already sorted based on some key and if we INSERT the data then it may disturb the SORT order. To avoid this first READ the table WITH BINARY SEARCH. Sy-subrc value will be set to 4 and sy-tabix value will be set to a value where this record would have been if at all it exists.

Consider below example.

If we have internal table (i_tab) data like below.

F1 F2 F3

1 asd fgfr

3 fdf fdsf.

READ TABLE i_tab INTO wa_tab WITH KEY F1 = 2 BINARY SEARCH.

After this statement sy-subrc will be 4 and sy-tabix will be 2(Which is nothing but the position if a record with key F1 = 2 was there. So instead of appending and sorting again we can directly INSERT the record at this position.

7. Always Use FMs.

Page 18: ABAP Perofrmance Tuning

18

Always try to use function modules instead of doing the calculations manually. We have SAP provided FMs readily available for most of the requirements. We need to find the correct one which suits our requirement.

Another advantage of using FMs is if at all any changes happen in future upgrades FMs will take care of these changes. Some of the best examples where we can use FM instead of coding our own logic or selecting data from tables are.

1. Getting customer address by using FM ADDR_GET2. Getting user details by using BAPI_USER_GET_DETAIL3. Getting change documents using FMs CHANGEDOCUMENT_READ_HEADERS and

CHANGEDOCUMENT_READ_POSITIONS will be faster than getting data from CDHDR and CDPOS tables.

4. Currency/Quantity/Date conversions.5. Converting some fields to internal/external format

E.g. Adding or deleting leading zeros by using FM CONVERSION_EXIT_ALPHA_INPUT / OUTPUT.

8. Usage of FREE Statement:

We can use this statement to relieve the memory occupied by the internal table. If we are sure that we don’t use internal table anymore then use FREE i_itab to relieve the internal memory occupied by the table. This statement causes slight improvement in performance only when the number of internal tables is more. When internal memory is not sufficient while executing program we will get a runtime error. But practically this situation may not arise.

9. Use BAPI instead of BDC.

Always search for some BAPI before starting the coding using BDC. BDC is already obsolete in the current versions of SAP.

10.Conditional statements.

In programming we will be using so many conditional statements which are also performance barriers. By taking proper care of the design we can enhance the performance.

a. Always try to avoid use of Negative statements like NOT IN, IF NOT.b. Replace Nested ifs/ If elseif… elseif…else…with CASE statement.c. Where ever possible replace IF statement by CHECK statement.

11.Data declarations:

Page 19: ABAP Perofrmance Tuning

19

Wonder how the data declarations affect the performance? It’s true from the analysis.It is advisable to do the data declarations inside the Local FORMs unless it is not being used at multiple places. If we don’t use some variable at more than one place then what is the need of declaring it in the global space and using global memory throughout the execution of the program? It may not directly affect the performance but above explanation makes sense.

Some useful transactions:

1. SE30:

SE30 is the one of the best transactions provided by SAP to learn the optimization techniques. There are thousands of techniques available which can be used to achieve simple to complex requirements in most optimal way. Below simple example shows how to analyze a report by using SE30.

STEPS:

1. Fill in initial screen as shown below with your transaction/report/FM name to be analyzed.

Page 20: ABAP Perofrmance Tuning

20

2. Next press on execute button, Now you will be directed to the program selection screen. Fill in the selection screen values, execute and come back after output is displayed.

Page 21: ABAP Perofrmance Tuning

21

3. Now you will be in initial screen again and gets a message saying measurement ended. Now press analyze button.

4. Below screen will be displayed.

Page 22: ABAP Perofrmance Tuning

22

5. Here we can observe 3 things. Time taken from ABAP side i.e. Business logic, Time taken by the operations performed on database i.e. Select statements and the final one is R/3 system which is time taken for system operations. Here u can observe time taken at data base level is near to 94%. This is because we are not passing even single primary key to the select statements. That is why the database time is more.

For better performance, ABAP time should be around 70% to 90%, database time should be 5% to 10% - and R/3 system time should be around 20% - 30%.

To do a detailed performance analysis check below transactions.

ST05: SQL, Enqueue, Dequeue and RFC trace.

ST30: Global Performance Analysis

STAD: Statistical Records.

Typical performance tuning check list:

http://www.saptechnical.com/Tutorials/ABAP/PerformanceCheckList.htm

References:

www.help.sap.com

www.sdn.sap.com

www.saptechnical.com