How to write efficient code in SAP Cloud Application Studio(SDK) for C4C?
I was having 2 ways to write a code, to check if a current user logged in to the system is having a particular business role(SAPC4C_MASSUPDATE)?
Both the code logic below return the same result.
Code Logic 1:
Code Logic 2:
Code Logic 1 does the task in a single line but Code logic 2 does the logic in multiple lines.
Efficient code takes less time to execute and how to decide which logic takes lesser time to execute?
SAP Cloud Application Studio’s ‘Trace’ class and its built-in method ‘Runtime’ comes to help.
There are 2 overloaded implementation of the method Trace.Runtime() as shown below:
- Trace.Runtime(String, Indicator);
Use the implementation Trace.Runtime(String, Indicator); at the start of the logic.
Use the Trace.Runtime(String); implementation at the end of the logic.
After rewriting the code with the Trace.Runtime() implementation, my Logic 1 code will now look line below:
In the Runtime method, for String parameter you can write any message text, with which you can Identify in the Trace log file.
In the Runtime method, for Indicator(Boolean) parameter , I have used ‘True’ because it tells the system to reset and start the time counter for code logic run-time measurement.
A sample trace result for the above code I have written would look like below, which tells exactly ‘how much time was spent by the system on a particular logic execution’:
For me both the Logic 1 and Logic 2 was returning similar results, So I decided to choose the Logic with less code for better maintainability.
Based on your scenario, you can run this Runtime Trace to make any decision for efficient code.
Some points to be noted when executing the Runtime trace:
- When you have 2 different logic , first run the trace with 1st logic in ABSL file and note the time. Then we have to replace the 1st logic with the 2nd logic in ABSL file and run the trace again to note the time for 2nd logic.
- Sometimes the order in which the logic is written in ABSL file will decide the time taken to run the code.So we have to test the logic separately as mentioned in the point 1.
- After all your testing with Trace statements, don’t forget to remove your Trace statements before moving your code to production.
Refer the Blog on how to execute trace in Cloud Application Studio, if you are not aware of the steps to take trace.
Runtime Trace is just one tool to decide on the efficient logic in your code, you should also refer to the Performance Check and Performance Best Practice blogs to write efficient Cloud Application Studio code