关于abap的loop嵌套循环性能优化
在abap开发中经常会遇到两个内表之间的loop嵌套操作,在数据量小的时候无所谓,但是项目上线数据量增大的时候程序的性能问题就会体现出来,100和1000的两个内表嵌套就会是十万次循环,所以,在开发过程中尤其要注意对循环结构的优化。
# 错误实例
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
* 这样做效率最差
*优化后
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内表经过排序,在不满足条件的条目出现后就可以结束循环了。