Tuesday, August 6, 2019

Performance of Sorted Internal Table

Performance of Sorted table is much higher than normal table. The following technique proves that using a simple thing can raise the performance much better.

TYPESBEGIN OF ty_mara,
         matnr LIKE mara-matnr,
         mtart LIKE mara-mtart,
       END OF ty_mara.

DATAt_mara1 TYPE SORTED TABLE OF ty_mara
      WITH NON-UNIQUE KEY mtart.
DATAw_counter TYPE i,
      w_tabix   LIKE sy-tabix.

SELECT matnr,                           " Material Number
       mtart                            " Material Type
  FROM mara
  INTO TABLE @DATA(t_mara).

SORT t_mara BY mtart.
t_mara1 t_mara.

* CASE 1: Processing internal table using LOOP..WHERE Condition
GET RUN TIME FIELD DATA(w_runtime1).
LOOP AT t_mara ASSIGNING FIELD-SYMBOL(<w_mara>)
  WHERE mtart EQ 'ZROH'.
  ADD TO w_counter.
ENDLOOP.
GET RUN TIME FIELD DATA(w_runtime2).
* Calculate Runtime
w_runtime2 w_runtime2 w_runtime1.
WRITE:/ w_runtime2'for Records'w_counter.
CLEAR w_counter.


* CASE 2: Using a Sorted table
GET RUN TIME FIELD w_runtime1.
LOOP AT t_mara1 ASSIGNING <w_mara> WHERE mtart EQ 'ZROH'.
  ADD TO w_counter.
ENDLOOP.
GET RUN TIME FIELD w_runtime2.
* Calculate Runtime
w_runtime2 w_runtime2 w_runtime1.
WRITE:/ w_runtime2'for Records'w_counter.
CLEAR w_counter.


* CASE 3: Using INDEX on a sorted table
GET RUN TIME FIELD w_runtime1.
READ TABLE t_mara1 ASSIGNING <w_mara> WITH KEY mtart 'ZROH'.
IF sy-subrc EQ 0.
  w_tabix sy-tabix + 1.
  ADD TO w_counter.
  LOOP AT t_mara1 ASSIGNING <w_mara> FROM w_tabix.
    IF <w_mara>-mtart NE 'ZROH'.
      EXIT.
    ENDIF.
    ADD TO w_counter.
  ENDLOOP.
ENDIF.
GET RUN TIME FIELD w_runtime2.
* Calculate Runtime
w_runtime2 w_runtime2 w_runtime1.
WRITE:/ w_runtime2'for Records'w_counter.


Different output at different time.


It's very clear that the high performance can be achieved by using this simple technique.

No comments: