π Scenario
Consider the following code:
DATA: lt_mara TYPE TABLE OF mara.
SELECT *
FROM mara
INTO TABLE lt_mara.
LOOP AT lt_mara INTO DATA(ls_mara).
READ TABLE lt_mara
INTO DATA(ls_temp)
WITH KEY matnr = ls_mara-matnr.
ENDLOOP.
❓ Question
1️⃣ What is the time complexity of this code?
2️⃣ How would you optimize it? Specifically explain:
- ✅ Standard Table
- ✅ Sorted Table
- ✅ Hashed Table
π And which one would you choose and why?
π Time Complexity Analysis
1️⃣ Standard Table π²
Default table type. READ TABLE performs linear search.
- LOOP → O(N)
- READ TABLE → O(N)
- Overall → O(N²) ⚠️
⚠️ Performance degrades badly for large datasets.
2️⃣ Sorted Table πΆ
Data is sorted by key. READ TABLE uses binary search.
- LOOP → O(N)
- READ TABLE → O(log N)
- Overall → O(N log N)
⭐ Good choice when:
- Data must remain sorted
- Range access is required
- Partial key searches are common
3️⃣ Hashed Table #️⃣
Uses hash algorithm for key access.
- LOOP → O(N)
- READ TABLE → O(1)* (average case)
- Overall → O(N)
π Best suited for:
- Frequent key-based lookups
- Exact key searches
- Large datasets
*(Average Case)
π My Choice
If the requirement is purely key-based access using MATNR, I would choose a Hashed Table because lookup is approximately O(1), making the overall complexity O(N).
WITH UNIQUE KEY matnr.✅ Fastest lookup for exact key access!
⚠️ Hidden Performance Issue
In this example, the READ TABLE is actually redundant.
π‘ We are already looping over the same table, and the current record is already available in ls_mara.
❌ The additional READ TABLE provides no business value and only adds unnecessary processing.
π Interview Tip
Many developers immediately answer:
π "Use a Hashed Table."
A stronger answer is:
π "First, I would question whether the READ TABLE is needed at all."
Removing unnecessary logic is often a bigger optimization than changing the table type.
π¬ Bonus Question
Would you still choose a Hashed Table if the requirement involved:
- π Range searches
- π Partial key searches
- ↕️ Sorted output
Why or why not? Let's discuss in the comments! π
π‘ Choose the right table type. Remove unnecessary logic. Write efficient ABAP.
No comments:
Post a Comment