Friday, July 29, 2022

Replacing LOOP statement with ABAP Filter Operator

I tried to compare how ABAP filter operator compete with LOOP statement.

 

1. Classic LOOP statement

On top of itab t_data that is being looped over into a structure a new itab t_data1 is generated from the structure. A condition for the LOOP specified as hardcoded into WHERE part of the LOOP statement.

LOOP AT t_data INTO s_data WHERE ( col_1 = 'AAA' ).

  INSERT s_data INTO TABLE t_data1.

ENDLOOP.

 

2. Filter Operator

A Filter Operator is used to build the itab t_data2 based on th_data itab. Condition is specified as hardcoded one in the filter.

DATA(t_data2) = FILTER #( th_data WHERE col_1 = 'AAA' ).

 

Next, let assume that we have a multiple conditions for the LOOP so they are stored in a special itabs.

3. Classic LOOP statement with WHERE condition as a range

In a case of the class LOOP statement I leveraged range type of itab. The range (t_filter itab) is prepared prior the LOOP. Afterwards the range in used in the WHERE part of the LOOP by IN statement.

t_filter = VALUE #( BASE t_filter ( opt = 'EQ' sign = 'I' low = 'AAA' ) ).
 
LOOP AT th_data INTO s_data WHERE col_1 IN t_filter.
  INSERT s_data INTO TABLE t_data3.
ENDLOOP.

 

4. FILTER Operator with filter as itab

A hash itab (th_filter) is prepared with the condition prior the FILTER operator statement. A new itab (t_data4) is prepared by Filter operator. The Filter operator uses IN statement to specified the itab with the filter.

th_filter = VALUE #( BASE th_filter ( col_1 = 'AAA' ) ).
 
DATA(t_data4) = FILTER #( th_data IN th_filter WHERE col_1 = col_1 ).

 

Conclusion

In my system based on component SAP_ABA 75, SP04 I achieved the fastest the run no 2. Means Filter operator where the condition was hardcoded.



Few more remarks:

To count the no of the itab entries I used REDUCE (Reduction Operator – part of Iteration expression). The statement basically goes over all the entries of the itab and adding 1 into n variable as specified in NEXT statement.

v_count = REDUCE i( INIT n = 0 FOR x_data IN t_data4 NEXT n = n + 1 ).

 

Yes, I’m aware that I could do this by lines (a row function) as seen below. However, I wanted to try more the reduce operator instead.

DATA(v_cnt) = lines( t_data1 )

 

To calculate total of figure that is stored in column col_f in all the itabs I used again Reduction Operator. Just in this case the value of the column col_f is being added up into n variable.

v_count = REDUCE i( INIT n = 0 FOR x_data IN t_data4 NEXT n = n + x_data-col_f ).

Source code available in my Gitgub gist zmm_loop_replacement

No comments: