關于abap的loop嵌套循環(huán)性能優(yōu)化
在abap開發(fā)中經常會遇到兩個內表之間的loop嵌套操作熊赖,在數(shù)據(jù)量小的時候無所謂弯汰,但是項目上線數(shù)據(jù)量增大的時候程序的性能問題就會體現(xiàn)出來矾瑰,100和1000的兩個內表嵌套就會是十萬次循環(huán)衷佃,所以欺冀,在開發(fā)過程中尤其要注意對循環(huán)結構的優(yōu)化侈离。
# 錯誤實例
DATA: BEGIN OF LT_DATA1 OCCURS 0,
ROW1 TYPE C,
ROW2 TYPE I,
END OF IT_DATA1.
DATA: BEGIN OF LT_DATA2 OCCURS 0,
ROW1 TYPE C,
ROW2 TYPE I,
END OF IT_DATA2.
DATA: LV_ROW2 TYPE I.
LV_ROW2 = 1.
LT_DATA1-ROW1 = A.
LT_DATA1-ROW2 = LV_ROW2.
APPEND LT_DATA1.
LT_DATA1-ROW1 = A.
LT_DATA1-ROW2 = LV_ROW2.
APPEND LT_DATA1 , LT_DATA2.
CLEAR: LT_DATA1, LT_DATA2.
LV_ROW2 = LV_ROW2 + 1.
LT_DATA1-ROW1 = B.
LT_DATA1-ROW2 = LV_ROW2.
APPEND LT_DATA1.
LT_DATA1-ROW1 = B.
LT_DATA1-ROW2 = LV_ROW2.
APPEND LT_DATA1 , LT_DATA2.
CLEAR: LT_DATA1, LT_DATA2.
LV_ROW2 = LV_ROW2 + 1.
LT_DATA1-ROW1 = C.
LT_DATA1-ROW2 = LV_ROW2.
APPEND LT_DATA1.
LT_DATA1-ROW1 = C.
LT_DATA1-ROW2 = LV_ROW2.
APPEND LT_DATA1 , LT_DATA2.
CLEAR: LT_DATA1, LT_DATA2.
LV_ROW2 = LV_ROW2 + 1.
LOOP AT LT_DATA1.
WRITE :\, LT_DATA1-ROW1,LT_DATA1-ROW2.
CLEAR LT_DATA1.
END LOOP.
LOOP AT LT_DATA2.
WRITE :\, LT_DATA2-ROW1,LT_DATA2-ROW2.
CLEAR LT_DATA2.
END LOOP.
* 將2表的row2加到1表的row2對應的行項目上试幽。
LOOP AT LT_DATA1.
LOOP AT LT_DATA2 WHERE ROW1 = LT_DATA1-ROW1.
LT_DATA1-ROW2 = LT_DATA1-ROW2 + LT_DATA2-ROW2.
CLEAR : LT_DATA2.
ENDLOOP.
MODIFY LT_DATA1.
ENDLOOP
* 這樣做效率最差
*優(yōu)化后
DATA: LV_TABIX TYPE I.
SORT LT_DATA1 BY ROW1.
LOOP AT LT_DATA1.
READ TABLE LT_DATA2 WITH KEY ROW1 = LT_DATA1 BINARY SEARCH TRANSPORTING NO FIELDS.
IF SY-SUBRC = 0.
LV_TABIX = SY-TABIX.
CLEAR LT_DATA2
LOOP AT LT_DATA2 FROM LV_TABIX.
IF LTDATA1-ROW1 = LT_DATA2-ROW1.
LT_DATA1-ROW2 = LT_DATA1-ROW2 + LTDATA2-ROW2.
ELSE.
EXIT.
ENDIF.
CLEAR LT_DATA2.
ENDLOOP.
ENDIF
MODIFY LT_DATA1.
ENDLOOP.
* 首先查找是否存在滿足條件的2內表條目,通過索引從哪里開始遍歷卦碾,并且2內表經過排序铺坞,在不滿足條件的條目出現(xiàn)后就可以結束循環(huán)了起宽。