📋 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