Internal Tables
ABAP DevelopmentAdvanced

Nested LOOP Optimization and Parallel Cursor

Learn how to replace expensive nested loops with better lookup patterns.

Explanation

Nested loops are a common reason for ABAP performance problems. If one table has 50,000 rows and another has 50,000 rows, a naive nested LOOP can become extremely expensive. Older ABAP programs often used the parallel cursor technique after sorting both tables. In many modern cases, a HASHED or SORTED lookup table is easier and more maintainable. Parallel cursor is still useful to understand because it appears in legacy code and interviews, but new development should choose the simplest performant design. The goal is not to use a fancy technique, but to reduce repeated full-table scans.

Code example

ABAP Code
SORT lt_item BY vbeln. LOOP AT lt_header INTO DATA(ls_header).  LOOP AT lt_item INTO DATA(ls_item) WHERE vbeln = ls_header-vbeln.    APPEND ls_item TO lt_output.  ENDLOOP.ENDLOOP. * For unique lookup cases, prefer HASHED table with proper key.

Real project scenario

A report matches sales order header data with item data. Instead of looping all items for each header, sort items by VBELN and process only the matching range, or use a grouped/sorted access pattern.

Common mistakes

- Using full nested loops for large data. - Applying parallel cursor without understanding sorted order. - Using complex optimization where simple hashed lookup is enough. - Not measuring performance before and after change.

Best practices

- Avoid full nested scans on large tables. - Use hashed lookup for unique keys. - Use sorted range processing when multiple child rows exist. - Keep the optimized logic readable.

Interview angle

A senior answer should compare nested loops, sorted access, hashed lookup and parallel cursor with pros and cons.