Home > Mobile >  how to improve the performance in nested loops with 2 tables having huge number of entries in abap?
how to improve the performance in nested loops with 2 tables having huge number of entries in abap?

Time:10-15

Both tables sorted by key KNO

    LOOP AT lt_header INTO lwa_header.

         LOOP AT lt_items INTO lwa_item

                 WHERE key = lwa_header-KNO

                “……….

          ENDLOOP.

     ENDLOOP.

This would take more time to execute if number of entries in the table is huge. How should i modify code to improve the performance?

CodePudding user response:

You should be able to improve the lookup in the second table by using a secondary table key. Such a key needs to be declared when you declare the table variable:

DATA lt_items TYPE TABLE OF whatever WITH NON-UNIQUE SORTED KEY k1 COMPONENTS key.

You can then use this key to accelerate lookups in that table from O(n) or O(log n) time complexity:

LOOP AT lt_header INTO lwa_header.
  LOOP AT lt_items INTO lwa_item
          USING KEY k1
          WHERE key = lwa_header-KNO.
    "...
  ENDLOOP.
ENDLOOP.

When you can guarantee that the values in lt_items-key are always unique (there are no two lines with the same value for "key"), then you can even use a hashed key, which is even faster (constant time):

DATA lt_items TYPE TABLE OF whatever WITH UNIQUE HASHED KEY k1 COMPONENTS key.

LOOP AT lt_header INTO lwa_header.
  READ TABLE lt_items INTO lwa_item
          WITH TABLE KEY k1
          COMPONENTS key = lwa_header-KNO.
  IF sy-subrc = 0.
     "...
  ENDIF.
ENDLOOP.

CodePudding user response:

You can use parallel cursor. It's a good technique for performance improvements in nested loops. For more information check this link.

Also field symbols are better for performance.

DATA lv_tabix TYPE sy-tabix.

SORT: lt_header BY kno,
      lt_items BY kno.

LOOP AT lt_header ASSIGNING FIELD-SYMBOL(<lfs_header>).
 READ TABLE lt_items TRANSPORTING NO FIELDS
                     WITH KEY kno = <lfs_header>-kno
                     BINARY SEARCH.
 lv_tabix = sy-tabix.
 LOOP AT lt_items FROM lv_tabix ASSIGNING FIELD-SYMBOL(<lfs_item>).
   IF <lfs_header>-kno <>  <lfs_item>-kno.
     EXIT.
  ENDIF.
  "Your logic should be here..
 ENDLOOP.
ENDLOOP.
  • Related