Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

Code Optimization Techniques

Former Member
0 Kudos

Hi SDN Users,

Could anyone can send me the 'Code Optimization' Techniques.

General Rules and Methodoligies need to follow.

Thanks,

Jayaram

1 ACCEPTED SOLUTION

Former Member

hi,

Run Extended syntax checks with character literals checkbox switched on & Code Inspector to rectify all relevant errors and warning (e.g. Use the results of the above checks to remove all variables/constants etc that are declared but are not used)

Transaction SE30 (ABAP Runtime Analysis) must be checked to measure/compare program performance/runtime if program has multiple inefficient databases selects or complicated internal table operations

Use transaction ST05 (SQL Trace) to see what indices your database accesses are using. Check these indices against your “where” clause to assure they are significant. Check other indices for this table and where you have to change your “where” clause to use it. Create new indices if necessary, but do not forget to check the impact by consulting onsite coordinator.

TYPE (data element) command is used while declaring the fields whenever feasible instead of LIKE. Remember not always the data element name matches with the table field name

Internal Table is defined with “TYPE STANDARD TABLE OF” & Work-Areas is used instead of header lines

Global variables are minimized by declaring local variables or by passing variables through parameters & arguments while creating internal subroutine(s)

In SELECT statement, only the required fields are selected in the same order as they reside on the database table/structure/view

For selecting single row from a database table, “SELECT UP to 1 Rows” is used. “Select Single” is used only when full primary key combination is known

No SELECT * is used

Use “SELECT INTO TABLE” rather than “SELECT INTO CORRESPONDING FIELDS OF TABLE”

Always specify as many primary keys as possible in WHERE clause to make the Select efficient

Always select into an internal table, except when the table will be very large (i.e., when the internal table will be greater than 500,000 records). Use “Up to N Rows” when the number of records needed is known

Select statement within a GET event is not used

Wild cards like ‘A%’ is avoided as much as possible

Nested Select is not used instead “Inner Join” and/or “For all Entries” is used. “For all Entries” is to be used over “Loop at ITAB / Select / ENDLOOP” (FOR ALL ENTRIES retrieves a unique result set so ensure you retrieve the full key from the database)

When creating joins over database tables there should be an index at least on the inner table for the fields in the join condition else use “ FOR ALL ENTRIES” select statement

Usage of JOIN is limited to a maximum of 2 i.e. not more than 3 database tables are joined at one time

CHECK that the internal table used in FOR ALL ENTRIES is NOT empty as this will retrieve all entries from the table

Delete adjacent duplicate entries from internal table before selection from database table using “ FOR ALL ENTRIES” statement

For copying internal tables use ‘=’ operator instead of Looping & Appending

SORT inside a LOOP is not used

Sort internal table by fields in the correct order, which are used in a READ TABLE statement using BINARY SEARCH. If the order of sorting is invalid the BINARY SEARCH will never work

For large internal tables where only some rows are to be processed, use SORT and then the READ TABLE command is used to set index to first relevant row before looping from that index. Use CHECK or IF…EXIT…ENDIF as appropriate to exit from the loop

Sort fields and Sort Order on the SORT statement should be mentioned explicitly (e.g. SORT ITAB BY FLD1 FLD2 ASCENDING)

Hashed table is used for processing large amount of data (provided that you access single records only, and all with a fully specified key)

DELETE or SORT is not used on a hashed table since it increases memory consumption

Sorted table is used for range accesses involving table key or index accesses

Fields specified in the WHERE condition with the critical operators NOT and <> (negative SQL statements) cannot be used for a search using database indexes. Whenever possible formulate SQL statements positively

When coding IF or CASE, testing conditions are nested so that the most frequently true conditions are processed first. Also CASE is used instead of IF when testing multiple fields “equal to” something

LOOP AT ITAB INTO WORKAREA WHERE K = ‘XXX’ should be used instead of LOOP AT ITAB INTO WORKAREA / CHECK ITAB-K = ‘XXX’.

Also READ TABLE INTO WORKAREA should be used instead of only READ TABLE.

After the APPEND statement inside a loop, the work area that has been appended is cleared

Internal tables, Work areas & Global Variables are freed when no longer needed (e.g. using the FREE / REFRESH command), especially when the tables are large or the program is a batch program

Do not delete the records of internal table inside the Loop – End loop.

Do not use: LOOP AT ITAB WHERE EQUNR = ‘00001011’.

DELETE ITAB.

ENDLOOP.

Use: DELETE ITAB WHERE EQUNR = ‘00001011’.

Use the MODIFY ITAB ... TRANSPORTING f1 f2 ... for single line, and MODIFY ITAB ... TRANSPORTING f1 f2 ... WHERE condition for a set of line, to accelerate the updating of internal table

If possible, Update/Insert statement is used instead of Modify

Is the following steps ensured during database updates?

Lock data to be edited

Read current data from the database

Process data and write it to the database

Release the locks set at the beginning

Try to avoid logical databases. If your program uses a logical database, but does not require all fields belonging to a certain GET event, always use the FIELDS addition to reduce the amount of data selected by the logical database

Avoid the aggregate (Count, Max, Min) functions in the database selection

Use Parallel Cursor methods for nested loop into the internal tables if second internal table contains considerable number of records

In Smartform/ Sapscript do not make redundant data retrieval where data is available in interface

Hope this helps, Do reward.

5 REPLIES 5

Former Member

hi,

Run Extended syntax checks with character literals checkbox switched on & Code Inspector to rectify all relevant errors and warning (e.g. Use the results of the above checks to remove all variables/constants etc that are declared but are not used)

Transaction SE30 (ABAP Runtime Analysis) must be checked to measure/compare program performance/runtime if program has multiple inefficient databases selects or complicated internal table operations

Use transaction ST05 (SQL Trace) to see what indices your database accesses are using. Check these indices against your “where” clause to assure they are significant. Check other indices for this table and where you have to change your “where” clause to use it. Create new indices if necessary, but do not forget to check the impact by consulting onsite coordinator.

TYPE (data element) command is used while declaring the fields whenever feasible instead of LIKE. Remember not always the data element name matches with the table field name

Internal Table is defined with “TYPE STANDARD TABLE OF” & Work-Areas is used instead of header lines

Global variables are minimized by declaring local variables or by passing variables through parameters & arguments while creating internal subroutine(s)

In SELECT statement, only the required fields are selected in the same order as they reside on the database table/structure/view

For selecting single row from a database table, “SELECT UP to 1 Rows” is used. “Select Single” is used only when full primary key combination is known

No SELECT * is used

Use “SELECT INTO TABLE” rather than “SELECT INTO CORRESPONDING FIELDS OF TABLE”

Always specify as many primary keys as possible in WHERE clause to make the Select efficient

Always select into an internal table, except when the table will be very large (i.e., when the internal table will be greater than 500,000 records). Use “Up to N Rows” when the number of records needed is known

Select statement within a GET event is not used

Wild cards like ‘A%’ is avoided as much as possible

Nested Select is not used instead “Inner Join” and/or “For all Entries” is used. “For all Entries” is to be used over “Loop at ITAB / Select / ENDLOOP” (FOR ALL ENTRIES retrieves a unique result set so ensure you retrieve the full key from the database)

When creating joins over database tables there should be an index at least on the inner table for the fields in the join condition else use “ FOR ALL ENTRIES” select statement

Usage of JOIN is limited to a maximum of 2 i.e. not more than 3 database tables are joined at one time

CHECK that the internal table used in FOR ALL ENTRIES is NOT empty as this will retrieve all entries from the table

Delete adjacent duplicate entries from internal table before selection from database table using “ FOR ALL ENTRIES” statement

For copying internal tables use ‘=’ operator instead of Looping & Appending

SORT inside a LOOP is not used

Sort internal table by fields in the correct order, which are used in a READ TABLE statement using BINARY SEARCH. If the order of sorting is invalid the BINARY SEARCH will never work

For large internal tables where only some rows are to be processed, use SORT and then the READ TABLE command is used to set index to first relevant row before looping from that index. Use CHECK or IF…EXIT…ENDIF as appropriate to exit from the loop

Sort fields and Sort Order on the SORT statement should be mentioned explicitly (e.g. SORT ITAB BY FLD1 FLD2 ASCENDING)

Hashed table is used for processing large amount of data (provided that you access single records only, and all with a fully specified key)

DELETE or SORT is not used on a hashed table since it increases memory consumption

Sorted table is used for range accesses involving table key or index accesses

Fields specified in the WHERE condition with the critical operators NOT and <> (negative SQL statements) cannot be used for a search using database indexes. Whenever possible formulate SQL statements positively

When coding IF or CASE, testing conditions are nested so that the most frequently true conditions are processed first. Also CASE is used instead of IF when testing multiple fields “equal to” something

LOOP AT ITAB INTO WORKAREA WHERE K = ‘XXX’ should be used instead of LOOP AT ITAB INTO WORKAREA / CHECK ITAB-K = ‘XXX’.

Also READ TABLE INTO WORKAREA should be used instead of only READ TABLE.

After the APPEND statement inside a loop, the work area that has been appended is cleared

Internal tables, Work areas & Global Variables are freed when no longer needed (e.g. using the FREE / REFRESH command), especially when the tables are large or the program is a batch program

Do not delete the records of internal table inside the Loop – End loop.

Do not use: LOOP AT ITAB WHERE EQUNR = ‘00001011’.

DELETE ITAB.

ENDLOOP.

Use: DELETE ITAB WHERE EQUNR = ‘00001011’.

Use the MODIFY ITAB ... TRANSPORTING f1 f2 ... for single line, and MODIFY ITAB ... TRANSPORTING f1 f2 ... WHERE condition for a set of line, to accelerate the updating of internal table

If possible, Update/Insert statement is used instead of Modify

Is the following steps ensured during database updates?

Lock data to be edited

Read current data from the database

Process data and write it to the database

Release the locks set at the beginning

Try to avoid logical databases. If your program uses a logical database, but does not require all fields belonging to a certain GET event, always use the FIELDS addition to reduce the amount of data selected by the logical database

Avoid the aggregate (Count, Max, Min) functions in the database selection

Use Parallel Cursor methods for nested loop into the internal tables if second internal table contains considerable number of records

In Smartform/ Sapscript do not make redundant data retrieval where data is available in interface

Hope this helps, Do reward.

0 Kudos

Hi Runal singh,

Thanks for your information.

Regards,

Jayaram

Former Member
0 Kudos

hi

For all entries

The for all entries creates a where clause, where all the entries in the driver table are combined with OR. If the number of entries in the driver table is larger than rsdb/max_blocking_factor, several similar SQL statements are executed to limit the length of the WHERE clause.

The plus

Large amount of data

Mixing processing and reading of data

Fast internal reprocessing of data

Fast

The Minus

Difficult to program/understand

Memory could be critical (use FREE or PACKAGE size)

Some steps that might make FOR ALL ENTRIES more efficient:

Removing duplicates from the the driver table

Sorting the driver table

If possible, convert the data in the driver table to ranges so a BETWEEN statement is used instead of and OR statement:

FOR ALL ENTRIES IN i_tab

WHERE mykey >= i_tab-low and

mykey <= i_tab-high.

Nested selects

The plus:

Small amount of data

Mixing processing and reading of data

Easy to code - and understand

The minus:

Large amount of data

when mixed processing isn’t needed

Performance killer no. 1

Select using JOINS

The plus

Very large amount of data

Similar to Nested selects - when the accesses are planned by the programmer

In some cases the fastest

Not so memory critical

The minus

Very difficult to program/understand

Mixing processing and reading of data not possible

Use the selection criteria

SELECT * FROM SBOOK.

CHECK: SBOOK-CARRID = 'LH' AND

SBOOK-CONNID = '0400'.

ENDSELECT.

SELECT * FROM SBOOK

WHERE CARRID = 'LH' AND

CONNID = '0400'.

ENDSELECT.

Use the aggregated functions

C4A = '000'.

SELECT * FROM T100

WHERE SPRSL = 'D' AND

ARBGB = '00'.

CHECK: T100-MSGNR > C4A.

C4A = T100-MSGNR.

ENDSELECT.

SELECT MAX( MSGNR ) FROM T100 INTO C4A

WHERE SPRSL = 'D' AND

ARBGB = '00'.

Select with view

SELECT * FROM DD01L

WHERE DOMNAME LIKE 'CHAR%'

AND AS4LOCAL = 'A'.

SELECT SINGLE * FROM DD01T

WHERE DOMNAME = DD01L-DOMNAME

AND AS4LOCAL = 'A'

AND AS4VERS = DD01L-AS4VERS

AND DDLANGUAGE = SY-LANGU.

ENDSELECT.

SELECT * FROM DD01V

WHERE DOMNAME LIKE 'CHAR%'

AND DDLANGUAGE = SY-LANGU.

ENDSELECT.

Select with index support

SELECT * FROM T100

WHERE ARBGB = '00'

AND MSGNR = '999'.

ENDSELECT.

SELECT * FROM T002.

SELECT * FROM T100

WHERE SPRSL = T002-SPRAS

AND ARBGB = '00'

AND MSGNR = '999'.

ENDSELECT.

ENDSELECT.

Select … Into table

REFRESH X006.

SELECT * FROM T006 INTO X006.

APPEND X006.

ENDSELECT

SELECT * FROM T006 INTO TABLE X006.

Select with selection list

SELECT * FROM DD01L

WHERE DOMNAME LIKE 'CHAR%'

AND AS4LOCAL = 'A'.

ENDSELECT

SELECT DOMNAME FROM DD01L

INTO DD01L-DOMNAME

WHERE DOMNAME LIKE 'CHAR%'

AND AS4LOCAL = 'A'.

ENDSELECT

Key access to multiple lines

LOOP AT TAB.

CHECK TAB-K = KVAL.

" ...

ENDLOOP.

LOOP AT TAB WHERE K = KVAL.

" ...

ENDLOOP.

Copying internal tables

REFRESH TAB_DEST.

LOOP AT TAB_SRC INTO TAB_DEST.

APPEND TAB_DEST.

ENDLOOP.

TAB_DEST[] = TAB_SRC[].

Modifying a set of lines

LOOP AT TAB.

IF TAB-FLAG IS INITIAL.

TAB-FLAG = 'X'.

ENDIF.

MODIFY TAB.

ENDLOOP.

TAB-FLAG = 'X'.

MODIFY TAB TRANSPORTING FLAG

WHERE FLAG IS INITIAL.

Deleting a sequence of lines

DO 101 TIMES.

DELETE TAB_DEST INDEX 450.

ENDDO.

DELETE TAB_DEST FROM 450 TO 550.

Linear search vs. binary

READ TABLE TAB WITH KEY K = 'X'.

READ TABLE TAB WITH KEY K = 'X' BINARY SEARCH.

Comparison of internal tables

DESCRIBE TABLE: TAB1 LINES L1,

TAB2 LINES L2.

IF L1 <> L2.

TAB_DIFFERENT = 'X'.

ELSE.

TAB_DIFFERENT = SPACE.

LOOP AT TAB1.

READ TABLE TAB2 INDEX SY-TABIX.

IF TAB1 <> TAB2.

TAB_DIFFERENT = 'X'. EXIT.

ENDIF.

ENDLOOP.

ENDIF.

IF TAB_DIFFERENT = SPACE.

" ...

ENDIF.

IF TAB1[] = TAB2[].

" ...

ENDIF.

Modify selected components

LOOP AT TAB.

TAB-DATE = SY-DATUM.

MODIFY TAB.

ENDLOOP.

WA-DATE = SY-DATUM.

LOOP AT TAB.

MODIFY TAB FROM WA TRANSPORTING DATE.

ENDLOOP.

Appending two internal tables

LOOP AT TAB_SRC.

APPEND TAB_SRC TO TAB_DEST.

ENDLOOP

APPEND LINES OF TAB_SRC TO TAB_DEST.

Deleting a set of lines

LOOP AT TAB_DEST WHERE K = KVAL.

DELETE TAB_DEST.

ENDLOOP

DELETE TAB_DEST WHERE K = KVAL.

Tools available in SAP to pin-point a performance problem

The runtime analysis (SE30)

SQL Trace (ST05)

Tips and Tricks tool

The performance database

Optimizing the load of the database

Using table buffering

Using buffered tables improves the performance considerably. Note that in some cases a stament can not be used with a buffered table, so when using these staments the buffer will be bypassed. These staments are:

Select DISTINCT

ORDER BY / GROUP BY / HAVING clause

Any WHERE clasuse that contains a subquery or IS NULL expression

JOIN s

A SELECT... FOR UPDATE

If you wnat to explicitly bypass the bufer, use the BYPASS BUFFER addition to the SELECR clause.

Use the ABAP SORT Clause Instead of ORDER BY

The ORDER BY clause is executed on the database server while the ABAP SORT statement is executed on the application server. The datbase server will usually be the bottleneck, so sometimes it is better to move thje sort from the datsbase server to the application server.

If you are not sorting by the primary key ( E.g. using the ORDER BY PRIMARY key statement) but are sorting by another key, it could be better to use the ABAP SORT stament to sort the data in an internal table. Note however that for very large result sets it might not be a feasible solution and you would want to let the datbase server sort it.

Avoid ther SELECT DISTINCT Statement

As with the ORDER BY clause it could be better to avoid using SELECT DISTINCT, if some of the fields are not part of an index. Instead use ABAP SORT + DELETE ADJACENT DUPLICATES on an internal table, to delete duplciate rows.

TIPS & TRICKS FOR OPTIMIZATION

Use the GET RUN TIME command to help evaluate performance. It's hard to know whether that optimization technique REALLY helps unless you test it out. Using this tool can help you know what is effective, under what kinds of conditions. The GET RUN TIME has problems under multiple CPUs, so you should use it to test small pieces of your program, rather than the whole program.

Generally, try to reduce I/O first, then memory, then CPU activity. I/O operations that read/write to hard disk are always the most expensive operations. Memory, if not controlled, may have to be written to swap space on the hard disk, which therefore increases your I/O read/writes to disk. CPU activity can be reduced by careful program design, and by using commands such as SUM (SQL) and COLLECT (ABAP/4).

Avoid 'SELECT *', especially in tables that have a lot of fields. Use SELECT A B C INTO instead, so that fields are only read if they are used. This can make a very big difference.

Field-groups can be useful for multi-level sorting and displaying. However, they write their data to the system's paging space, rather than to memory (internal tables use memory). For this reason, field-groups are only appropriate for processing large lists (e.g. over 50,000 records). If you have large lists, you should work with the systems administrator to decide the maximum amount of RAM your program should use, and from that, calculate how much space your lists will use. Then you can decide whether to write the data to memory or swap space.

Use as many table keys as possible in the WHERE part of your select statements.

Whenever possible, design the program to access a relatively constant number of records (for instance, if you only access the transactions for one month, then there probably will be a reasonable range, like 1200-1800, for the number of transactions inputted within that month). Then use a SELECT A B C INTO TABLE ITAB statement.

Get a good idea of how many records you will be accessing. Log into your productive system, and use SE80 -> Dictionary Objects (press Edit), enter the table name you want to see, and press Display. Go To Utilities -> Table Contents to query the table contents and see the number of records. This is extremely useful in optimizing a program's memory allocation.

Try to make the user interface such that the program gradually unfolds more information to the user, rather than giving a huge list of information all at once to the user.

Declare your internal tables using OCCURS NUM_RECS, where NUM_RECS is the number of records you expect to be accessing. If the number of records exceeds NUM_RECS, the data will be kept in swap space (not memory).

Use SELECT A B C INTO TABLE ITAB whenever possible. This will read all of the records into the itab in one operation, rather than repeated operations that result from a SELECT A B C INTO ITAB... ENDSELECT statement. Make sure that ITAB is declared with OCCURS NUM_RECS, where NUM_RECS is the number of records you expect to access.

If the number of records you are reading is constantly growing, you may be able to break it into chunks of relatively constant size. For instance, if you have to read all records from 1991 to present, you can break it into quarters, and read all records one quarter at a time. This will reduce I/O operations. Test extensively with GET RUN TIME when using this method.

Know how to use the 'collect' command. It can be very efficient.

Use the SELECT SINGLE command whenever possible.

Many tables contain totals fields (such as monthly expense totals). Use these avoid wasting resources by calculating a total that has already been calculated and stored.

ABAP/4 Development Code Efficiency Guidelines

ABAP/4 (Advanced Business Application Programming 4GL) language is an "event-driven", "top-down", well-structured and powerful programming language. The ABAP/4 processor controls the execution of an event. Because the ABAP/4 language incorporates many "event" keywords and these keywords need not be in any specific order in the code, it is wise to implement in-house ABAP/4 coding standards.

SAP-recommended customer-specific ABAP/4 development guidelines can be found in the SAP-documentation.

This page contains some general guidelines for efficient ABAP/4 Program Development that should be considered to improve the systems performance on the following areas:-

Physical I/O - data must be read from and written into I/O devices. This can be a potential bottle neck. A well configured system always runs 'I/O-bound' - the performance of the I/O dictates the overall performance.

Memory consumption of the database resources eg. buffers, etc.

CPU consumption on the database and application servers

Network communication - not critical for little data volumes, becomes a bottle neck when large volumes are transferred.

Policies and procedures can also be put into place so that every SAP-customer development object is thoroughly reviewed (quality – program correctness as well as code-efficiency) prior to promoting the object to the SAP-production system. Information on the SAP R/3 ABAP/4 Development Workbench programming tools and its features can be found on the SAP Public Web-Server.

-

-


CLASSIC GOOD 4GL PROGRAMMING CODE-PRACTICES GUIDELINES

Avoid dead-code

Remove unnecessary code and redundant processing

Spend time documenting and adopt good change control practices

Spend adequate time anayzing business requirements, process flows, data-structures and data-model

Quality assurance is key: plan and execute a good test plan and testing methodology

Experience counts

-

-


SELECT * FROM

ENDSELECT

In order to keep the amount of data which is relevant to the query the hit set small, avoid using SELECT+CHECK statements wherever possible. As a general rule of thumb, always specify all known conditions in the WHERE clause (if possible). If there is no WHERE clause the DBMS has no chance to make optimizations. Always specify your conditions in the Where-clause instead of checking them yourself with check-statements. The database system can also potentially make use a database index (if possible) for greater efficiency resulting in less load on the database server and considerably less load on the network traffic as well.

Also, it is important to use EQ (=) in the WHERE clause wherever possible, and analyze the SQL-statement for the optimum path the database optimizer will utilize via SQL-trace when necessary.

Also, ensure careful usage of "OR", "NOT" and value range tables (INTTAB) that are used inappropriately in Open SQL statements.

-

-


SELECT *

vs.

SELECT SINGLE *

If you are interested in exactly one row of a database table or view, use the SELECT SINGLE statement instead of a SELECT * statement. SELECT SINGLE requires one communication with the database system whereas SELECT * requires two.

-

-


SELECT * FROM

It is usually faster to use the INTO TABLE version of a SELECT statement than to use APPEND statements

-

-


SELECT ... WHERE + CHECK

vs.

SELECT using aggregate function

If you want to find the maximum, minimum, sum and average value or the count of a database column, use a select list with aggregate functions instead of computing the aggregates within the program. The RDBMS is responsible for aggregated computations instead of transferring large amount of data to the application. Overall Network, Application-server and Database load is also considerably less.

-

-


SELECT INTO TABLE

……….

ENDSELECT

If you process your data only once, use a SELECT-ENDSELECT loop instead of collecting data in an internal table with SELECT ... INTO TABLE. Internal table handling takes up much more space

-

-


Nested SELECT statements:

SELECT * FROM

ENDSELECT

To process a join, use a view wherever possible instead of nested SELECT statements.

Using nested selects is a technique with low performance. The inner select statement is executed several times which might be an overhead. In addition, fewer data must be transferred if another technique would be used eg. join implemented as a view in ABAP/4 Repository.

· SELECT ... FORM ALL ENTRIES

· Explicit cursor handling (for more information, goto Transaction SE30 – Tips & Tricks)

-

-


Nested select:

SELECT * FROM pers WHERE condition.

SELECT * FROM persproj WHERE person = pers-persnr.

... process ...

ENDSELECT.

ENDSELECT.

vs.

SELECT persnr FROM pers INTO TABLE ipers WHERE cond. ……….

SELECT * FROM persproj FOR ALL ENTRIES IN ipers

WHERE person = ipers-persnr

………... process .……………

ENDSELECT.

In the lower version the new Open SQL statement FOR ALL ENTRIES is used. Prior to the call, all interesting records from 'pers' are read into an internal table. The second SELECT statement results in a call looking like this (ipers containing: P01, P02, P03):

(SELECT * FROM persproj WHERE person = 'P01')

UNION

(SELECT * FROM persproj WHERE person = 'P02')

UNION

(SELECT * FROM persproj WHERE person = 'P03')

In case of large statements, the R/3's database interface divides the statement into several parts and recombines the resulting set to one. The advantage here is that the number of transfers is minimized and there is minimal restrictions due to the statement size (compare with range tables).

-

-


SELECT * FROM

Use a select list or a view instead of SELECT *, if you are only interested in specific columns of the table. If only certain fields are needed then only those fields should be read from the database. Similarly, the number of columns can also be restricted by using a view defined in ABAP/4 Dictionary. Overall database and network load is considerably less.

-

-


SELECT without table buffering support

vs.

SELECT with table buffering support

For all frequently used, read-only(few updates) tables, do attempt to use SAP-buffering for eimproved performance response times. This would reduce the overall Database activity and Network traffic.

-

-


Single-line inserts

LOOP AT

ENDLOOP

vs.

Array inserts

Whenever possible, use array operations instead of single-row operations to modify the database tables.

Frequent communication between the application program and database system produces considerable overhead.

-

-


Single-line updates

SELECT * FROM

Wherever possible, use column updates instead of single row updates to update your database tables

-

-


DO....ENDDO loop with Field-Symbol

vs.

Using CA operator

Use the special operators CO, CA, CS instead of programming the operations yourself

If ABAP/4 statements are executed per character on long strings, CPU consumprion can rise substantially

-

-


Use of a CONCATENATE function module

vs.

Use of a CONCATENATE statement

Some function modules for string manipulation have become obsolete, and should be replaced by ABAP statements or functions

STRING_CONCATENATE... ---> CONCATENATE

STRING_SPLIT... ---> SPLIT

STRING_LENGTH... ---> strlen()

STRING_CENTER... ---> WRITE..TO. ..CENTERED

STRING_MOVE_RIGHT ---> WRITE...TO...RIGHT-JUSTIFIED

-

-


Moving with offset

vs.

Use of the CONCATENATE statement

Use the CONCATENATE statement instead of programming a string concatenation of your own

-

-


Use of SEARCH and MOVE with offset

vs.

Use of SPLIT statement

Use the SPLIT statement instead of programming a string split yourself

-

-


Shifting by SY-FDPOS places

vs

Using SHIFT...LEFT DELETING LEADING...

If you want ot delete the leading spaces in a string use the ABAP/4 statements SHIFT...LEFT DELETING LEADING... Other constructions (with CN and SHIFT... BY SY-FDPOS PLACES, with CONDENSE if possible, with CN and ASSIGN CLA+SY-FDPOS(LEN) ...) are not as fast

-

-


Get a check-sum with field length

vs

Get a check-sum with strlen ()

Use the strlen () function to restrict the DO loop to the relevant part of the field, eg. when determinating a check-sum

follow the links

http://www.sapbrainsonline.com/ARTICLES/TECHNICAL/optimization/optimization.html

http://www.abapmaster.com/ - 41k

cheers

sharad

Former Member
0 Kudos

hi,

take help of this,

Performance Tuning

1.1 SELECT:

Always select the only the required fields from the database tables and give the filtering condition in the select statement itself.

Recommended

Select * from zflight where airln = ‘LF’ and fligh = ‘222’.

Endselect.

Using select * fetches all the fields from the table and thus occupies more memory.

Not recommended

SELECT * FROM DD01L INTO DD01L_WA

WHERE DOMNAME LIKE 'CHAR%'

AND AS4LOCAL = 'A'.

ENDSELECT.

Recommended

SELECT DOMNAME FROM DD01L

INTO DD01L_WA-DOMNAME

WHERE DOMNAME LIKE 'CHAR%'

AND AS4LOCAL = 'A'.

ENDSELECT.

Thus it is advisable to select only those fields that are needed, so that the database server passes only a small amount of data back.Also it is advisable to avoid selecting the data fields into local variables as this also puts unnecessary load on the server. Instead attempt must be made to select the fields into an internal table.

If all the fields of a table have to be selected then select * into table is better option then declaring explicit work area.

SELECT * FROM T006 INTO TABLE X006.

Use of FOR ALL Entries

Outer join can be created using this addition to the where clause in a select statement. It speeds up the performance tremendously, but the cons of using this variation are listed below

1. Duplicates are automatically removed from the resulting data set. Hence care should be taken that the unique key of the detail line items should be given in the select statement.

2. If the table on which the For All Entries IN clause is based is empty, all rows are selected into the destination table. Hence it is advisable to check before-hand that the first table is not empty.

3. If the table on which the For All Entries IN clause is based is very large, the performance will go down instead of improving. Hence attempt should be made to keep the table size to a moderate level.

1. Try to use aggregate functions.

Select max (fligh) from zflight into maxnu where airln = ‘LF’ and cntry = ‘IN’.

The other aggregate functions that can be used are min (to find the minimum value), avg (to find the average of a Data interval), sum (to add up a data interval) and count (counting the lines in a data selection).

2. Try to use views instead of tables if provided by SAP.

3. Whenever reading internal table into a work area then try to mention key if possible.

To copy contents of one internal table into another use this syntax.

Instead of loop on one into work area and appending work area to another.

TAB_DEST[] = TAB_SRC[].

1.2 READ

Always try to read internal table by passing key and read by Binary search.

And before doing this always sort your internal table (This is the primary condition for binary search).

Not Recommended

Read table int_fligh with key airln = ‘LF’.

Recommended

Read table int_fligh with key airln = ‘LF’ binary search.

Always read the required fields using TRANSPORTING f1 f2 …

read table i_vbap transporting posnr with key

vbeln = i_vbak-vbeln binary search.

1.3 Sort Statement

A linear search on internal table with large record size or large record numbers is time consuming. It is always a good practice to search a record by binary search after sorting. The difference is felt especially in the production environment where the live data is usually huge.

When an internal table is sorted without specifying the keys the default is used. Hence specify the fields to be sorted, which is more efficient than SORT ITAB.

Sorting an Internal Table, though done in the memory, is a unnecessary load on the processor. Try to fill the table with sorted values. If the SORTED BY clause cannot be used in the select statement, then sorting the Internal Table is inevitable.

Always try to sort by giving key.

Sort i_mara by matnr.

Or

Try to declare your table type sorted table of or type hashed table of

1.4 DELETE

Where appropriate using the following syntax, task of deleting a set of lines can be transferred to the kernel.

DELETE itable [FROM ...] [TO ...] WHERE ...

If possible, WHERE should be used together with FROM... and/or TO... to enhance performance.

The performance gain when using

DELETE itable WHERE....

Instead of

LOOP AT table WHERE ...

DELETE itable.

ENDLOOP.

Increases with the number of entries the internal table contains and the number of lines to be deleted.

When deleting adjacent duplicates use COMPARING fields as far as possible.

E.g. DELETE ADJACENT DUPLICATE ENTRIES from <itable>

COMPARING F1 F2…

DELETE ADJACENT DUPLICATES FROM ITAB COMPARING K.

1.5 MOVE

Instead of using the move-corresponding clause it is advisable to use the move statement instead. Attempt should be made to move entire internal table headers in a single shot, rather than moving the fields one by one.

It is always advisable not to write move corresponding because in this the system looks for identical data elements and then it assigns the value.

Always try to use move fields manually from one to other structure

1.6 NESTED LOOPS

Avoid nested looping on the internal tables. They eat up processor time.

If nested loops are unavoidable then,

Avoid the following:

SORT: I_vbak by vbeln, I_vbap by vbeln.

Loop at I_vbak

Loop at I_vbap where vbeln = I_vbak-vbeln.

Endloop.

Endloop.

Instead use:

SORT: I_vbak by vbeln, I_vbap by vbeln.

Loop at I_vbak

Read table I_vbap with key vbeln = I_vbak-vbeln

binary search transporting no fields.

Loop at I_vbap from sy-tabix.

If I_vbap-vbeln <> I_vbak-vbeln.

Exit.

EndIf.

Endloop.

Endloop.

1.7 DESCRIBE

DESCRIBE TABLE <itable> [LINES <l>] [OCCURS <n>] [KIND <k>]

To find out how many entries are in an internal table use DESCRIBE.

DESCRIBE TABLE ITAB LINES CNTLNS.

Is more efficient than

LOOP AT ITAB.

CNTLNS = CNTLNS + 1.

ENDLOOP.

1.8 FIELD CONVERSION

Use fields of type I for typical integral variables like indices.

Use numeric literals or named constants with a number type

instead of character strings if you are dealing with type-I

or integral type-P fields.

Use type-N fields only for pure

digit strings that are not intended for calculations, e.g.,

telephone numbers or parts of a date or time field.

1.9 CONTROL BREAK STATEMENTS

SAP recommends not to use control break events in loop statements which have a Where Clause. The outcome of the results cannot be predicted correctly. However it is a general practice to use these control break events even in loop statements, which have a Where Clause. It is always a good practice to avoid control break events in such cases. If the logic is complicated without events then populate a new internal table, which has the required records, and then use events with it.

In a LOOP which processes an internal table, you can use special control structures for control break processing. All these structures begin with AT and end with ENDAT. The sequence of statements which lies between them is then executed if a control break occurs.

You can use these key words for control break processing with internal tables only if a loop is actively processing an internal table and reference is to the innermost currently active loop.

The control level structure with internal tables is static. It corresponds exactly to the sequence of columns in the internal table (from left to right). In this context, the criteria according to which you sort the internal table are unimportant.

At the start of a new control level (i.e. immediately after AT), the following occurs in the output area of the current LOOP statement:

All character type fields (on the right) are filled with "*" after the current control level key.

All other fields (on the right) are set to their initial values after the current control level key.

Between AT and ENDAT, you can use SUM to insert the appropriate control totals in the numeric fields (see also ABAP Number Types) of the LOOP output area (on the right) after the current control level key. Summing is supported both at the beginning of a control level (AT FIRST, AT NEW f) and also the end of a control level (AT END OF f, AT LAST).

At the end of the control level processing (i.e. after ENDAT), the old contents of the LOOP output area are restored.

The main purpose of control break statements is to :

To display headings (AT FIRST)

To display Subheading (AT NEW)

To display subtotals (AT END OF )

To get grand total and Footer(AT LAST)

On change of - it can be used in any loops like do, loop at,etc.

2 SUBROUTINES

Whenever values need to be passed in a subroutine have type declarations assigned to the formal parameters. If no specific type declaration is possible then use TYPE ANY. This improves the performance. It is also recommended by SAP and can be noticed during extended program check (EPC) for the program.

When modularizing your program, use FORMS rather than FUNCTIONS whenever practical. A statement of PERFORM FORM < > requires significantly less resources and time than does a CALL FUNCTION < >.

2.1 EFFICIENT DATABASE SELECTION

The following basic guidelines need to be considered while retrieving data from the database:

&#61607; Avoid unnecessary database accesses

&#61607; Keep the number of data records small

&#61607; Reduce information transfer to application server

&#61607; Reduce the load on the database engine

&#61607; Use database locks and SAP enqueue.

Basic thing to be kept in mind is:

&#61607; Get the data in one single go as far as possible, thereby reducing the network traffic.

Always use the WHERE clause in the corresponding SQL statement. An application should read only those lines of the table that are necessary for the processing. Therefore formulate filter condition not through CHECK statements, rather through part of WHERE statements

Avoid using complex WHERE clauses since the system has to break them down into several individual statements for the database system

If all you are interested in is retrieving all possible values for a given table field (i.e. you do not want duplicates), then SELECT DISTINCT will provide that capability and will also restrict the amount of data passed back to the application to only the set of unique values.

Instead of using DISTINCT, the application might remove the duplicates by itself, e.g. using DELETE ADJACENT DUPLICATES. This should only be used if a small number of duplicates are expected.

2.2 MISCELLANOUS

1. Avoid Use of validations between SELECT and ENDSELECT. Rather, retrieve the data into an internal table and make your validations.

2. Use Aggregate functions along with the SELECT statement is better than looping through the entire set of records.

3. Nested select is a No No, instead of that use Joins or Views. This improves the readability to some extent also.

4. Always use INTO TABLE and FOR ALL ENTRIES where ever possible. While using FOR ALL ENTRIES, check if the table contains any entries.

5. Modifying a group of lines. Do not loop at all the records, rather use the MODIFY statement on the internal table as a whole.

6. READ TABLE always with BINARY SEARCH.

7. Try to align your WHERE clause in sync with the index.

8. Appropriate use of INNER JOIN

9. Use ABAP sort over ORDER BY.

10. Use simple tools like SE30 and ST05 to fine tune the programs.

reward if useful

kushagra