用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: BEGIN OF str_data, id TYPE int4, name TYPE string, END OF str_data.
DATA: l_dex TYPE 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的居多。 如果没有对性能上特别要求,应该没必要修改, 如果数量太大,而性能受到了严重影响的时候, 可以在优化其他的时候,试着修改下取数的算法。
欢迎关注订阅号:SAP学习记录 (SAPlearning )