Showing posts with label ABAP Performance Tuning. Show all posts
Showing posts with label ABAP Performance Tuning. Show all posts

Best Technique in ABAP - Using Hashed Internal Table

Hashed Internal table faster access

The source tables ITAB1 and ITAB2 are standard tables. It is assumed that ITAB1 takes more entries than ITAB2. Otherwise, the table with more entries must be computed with "DESCRIBE TABLE ... LINES ...".
Since both tables shall represent sets, it is assumed that their entries are unique with respect to component K.

The algorithm works with a temporary table with unique key K. The table is a copy of ITAB1 and is used to locate the entries being also contained in ITAB2. The matching entries are copied to ITAB3.

The left-hand and right-hand side differ only by the kind of the temporary table being used. For a hashed table, the READ statement in the LOOP is faster than for the sorted table.


Using a sorted table 



STAB1 = ITAB1.
REFRESH ITAB3.
LOOP AT ITAB2 ASSIGNING <WA>.
  READ TABLE STAB1 FROM <WA>
                   TRANSPORTING NO FIELDS.
  IF SY-SUBRC = 0.
    APPEND <WA> TO ITAB3.
  ENDIF.
ENDLOOP.

FREE STAB1.

Using a hashed table


HTAB1 = ITAB1.
REFRESH ITAB3.
LOOP AT ITAB2 ASSIGNING <WA>.
  READ TABLE HTAB1 FROM <WA>
                   TRANSPORTING NO FIELDS.
  IF SY-SUBRC = 0.
    APPEND <WA> TO ITAB3.
  ENDIF.
ENDLOOP.

FREE HTAB1.


For more Tutorials, visit ABAP Tutorials, Tips & Tricks and Certification Questions

Best Techniques in ABAP Programming - Internal table appending


Joining Two Internal Tables - Best Technique


If ITAB1 has n1 entries and ITAB2 has n2 entries, the time needed for joining ITAB1 and ITAB2 with the straightforward algorithm is O( n1 * log2( n2 ) ), whereas the parallel cursor approach takes only O( n1 + n2 ) time. 

The parallel cursor algorithm assumes that ITAB2 is a secondary table containing only entries also contained in primary table ITAB1. 

If this assumption does not hold, the parallel cursor algorithm gets slightly more complicated, but its performance characteristics remain the same. 

Normal Technique used by ABAPers  

LOOP AT ITAB1 INTO WA1.
  READ TABLE ITAB2 INTO WA2
             WITH KEY K = WA1-K BINARY SEARCH.
  IF SY-SUBRC = 0.
    " ...
  ENDIF.
ENDLOOP.

Parallel Cursor Technique

DATA: I TYPE I.

I = 1.
LOOP AT ITAB1 INTO WA1.
  do.
    READ TABLE ITAB2 INTO WA2 INDEX I.
    IF SY-SUBRC <> 0. EXIT. ENDIF.
    IF WA2-K < WA1-K.
      ADD 1 TO I.
    ELSEIF WA2-K = WA1-K.
      " ...
      ADD 1 TO I.
      EXIT.
    ELSE.
      EXIT.
    endif.
  enddo.
  if sy-subrc <> 0. exit. endif.
ENDLOOP.


For more Tutorials, visit ABAP Tutorials, Tips & Tricks and Certification Questions