Date
PARALLEL CURSOR
Why We Avoid Nested Loops in SAP ABAP
Nested loops (looping inside another loop) are generally avoided in SAP ABAP because
they lead to performance issues, especially when dealing with large datasets.
Problems with Nested Loops:
1. High Execution Time:
• If we have two tables with m and n records, a nested loop results in m × n iterations.
• Example: Looping through 10,000 records inside another loop with 10,000 records
results in 100 million iterations!
2. Database and Memory Overhead:
• Nested loops increase CPU and memory usage, leading to system slowdowns.
3. Unnecessary Data Reads:
• A loop inside another loop often performs repeated data searches, causing redundant
computations.
Parallel Cursor Technique
Parallel Cursor is an optimised way of handling two internal tables efficiently using
sorting and indexed access (READ TABLE). Instead of using a nested loop, we sort both
tables and use a single loop with an indexed read to improve performance.
How Parallel Cursor Works:
1. Sort both tables based on common key fields.
2. Use a single LOOP over the first table.
3. Use READ TABLE with BINARY SEARCH to fetch matching entries from the
second table.
4. Use an index variable to track the position in the second table and avoid unnecessary
looping.
Example of Parallel Cursor vs. Nested Loop
Bad Approach (Nested Loops)
LOOP AT lt_header INTO wa_header.
LOOP AT lt_item INTO wa_item WHERE header_id = wa_header-
header_id.
" Process matching records (Inefficient - Nested Loop)
ENDLOOP.
ENDLOOP.
Here, for each header record, we are looping through all item records, leading to huge
performance issues.
2
Optimised Approach (Parallel Cursor)
SORT lt_header BY header_id.
SORT lt_item BY header_id.
DATA: lv_index TYPE sy-tabix.
LOOP AT lt_header INTO wa_header.
LOOP AT lt_item INTO wa_item FROM lv_index WHERE header_id =
wa_header-header_id.
lv_index = sy-tabix. " Store current position to resume search from here
ENDLOOP.
ENDLOOP.
How This Works:
• Sorting ensures both tables are in sequential order.
• Single LOOP on lt_header (outer loop).
• No full scan of lt_item in the inner loop because it starts from the last matched position
(lv_index).
• This reduces unnecessary iterations, making it significantly faster than a nested loop.
3
Performance Comparison
Approach Execution Time Iterations (Example: 10,000 Headers, 10,000 Items)
Nested Loops Slow (minutes) 100,000,000 (m × n)
Parallel Cursor Fast (seconds) 10,000 (Optimized with indexing)
Key Benefits of Parallel Cursor:
✔ Reduces Loop Execution Time
✔ Minimizes Memory Usage
✔ Improves Overall Performance
✔ Avoids Redundant Data Reads
This technique is widely used in SAP ABAP when working with large tables. Let me
know if you need further clarification!