用se30的時候,看到一段雙重loop的代碼,本身寫了個例子測試了下
第二層loop不要用where判斷,會慢
直接使用他的index
代碼以下
REPORT
zlm_test_003.
DATA: t0
TYPE i,
t1
TYPE i,
t2
TYPE i,
t3
TYPE i,
t4
TYPE i,
t5
TYPE i,
t6
TYPE i,
tm
TYPE i.
DATA:
BEGINOF str_data,
id TYPE int4,
name TYPE string,
END OF str_data.
DATA:
l_dexTYPE int4.
DATA:
l_it_1 LIKE TABLE OF str_data WITH KEY id WITH HEADER LINE,
l_it_2 LIKE TABLE OF str_data WITH KEY id WITH HEADER LINE.
GET RUN TIME FIELD t1.
DO 10000 TIMES.
l_it_1-id = sy-index.
l_it_1-name = sy-index.
APPEND l_it_1.
l_it_2-id = sy-index.
l_it_2-name = sy-index.
APPEND l_it_2.
ENDDO.
GET RUN TIME FIELD t2.
t3 =
t2 - t1.
WRITE t3.
SKIP.
CLEAR:t1,t2,t3,t4.
"紀錄當前時間
GET RUN TIME FIELD t1.
SORT l_it_1 BY id ASCENDING.
*SORT l_it_2 BY id ASCENDING.
SORT l_it_2 BY id DESCENDING.
GET RUN TIME FIELD t1.
LOOP AT l_it_2 .
LOOP AT l_it_1
WHERE id
= l_it_2-id.
EXIT.
ENDLOOP.
ENDLOOP.
GET RUN TIME FIELD t2.
GET RUN TIME FIELD t3.
l_dex = 1.
LOOP AT l_it_2
.
LOOP AT l_it_1
FROM
l_dex.
IF l_it_1-id =l_it_2-id.
EXIT.
ELSE.
l_dex= l_dex + 1.
CONTINUE.
ENDIF.
" ...
ENDLOOP.
ENDLOOP.
GET RUN TIME FIELD t4.
t5 = t2 - t1.
t6 = t4 - t3.
WRITE:/ '使用where用時:', t5.
WRITE:/ '使用index用時',t6.
tm =
t6 - t5.
WRITE:/ 'index - where',tm.
執行結果
其實緣由,我本身的理解是:
第一種狀況用了where,本質仍是所有循環了。
第二種,我是用index,找到了就continue,最優是1,最差是N,這個複雜度你們應該也知道。
可是不少時候,loop套用loop的時候,第二層仍是使用where的居多。
若是沒有對性能上特別要求,應該不必修改,
若是數量太大,而性能受到了嚴重影響的時候,
能夠在優化其餘的時候,試着修改下多層loop裏的算法。