Performance Problem with Internal Tables being Read with WHERE Clause in LOOP AT Statement
If one use a LOOP AT statement with a WHERE clause, the whole TABLE will be read through not only the entriers that satifies the WHERE clause. This can lead to performance problems when a very large internal table is being read many times with a WHERE clause.
The solution is to sort the table on the keyfields, use a READ statment to find the first entry that satifies the key. Then you can start the loop here, and check for changes in the keyfield to exit the loop.
The following Code should not be applied:
loop at gi_mseg into g_mseg
where matnr = p_matnr and
werks = p_werks and
lgort = p_lgort and
sobkz = space,
Instead of above mentioned code one should applied the following:
* Sort internal table with entries from MSEG
sort gi_mseg by matnr werks lgort.
* Find index of first entry that satifies the where clause data:
l_tabix_from like sy-tabix.
read table gi_mseg with key matnr = p_matnr
werks = p_werks
lgort = p_lgort binary search
check sy-tabix > 0.
move sy-tabix to l_tabix_from.
* Loop over the table from l_tabix_from, check for changes in keyfields, and
* if necessary check other fields.
loop at gi_mseg into g_mseg from l_tabix_from.
if g_mseg-matnr <> p_matnr or
g_mseg-werks <> p_werks or
g_mseg-lgort <> p_lgort.
* Stop loop
* Check other fields
check g_mseg-sobkz = space.
Read Here for More SAP ABAP Tutorials