The mysteries of the RETURNING parameter
I really like the RETURNING parameter in ABAP OO, in my opinion it makes ABAP code more consistent and readable, see https://www.cqse.eu/en/blog/coding-abap-like-java/#keep-method-calls-simple-and-consistent for an example.
I use it whenever possible, also for deep structures and internal tables. However, the standard SAP code inspector check “Poor parameter pass performance” states that:
And RETURNING is always passed by value, which always gives a minimum of 40% performance loss!? And pass by value will use twice the memory?
Since memory is quite cheap, it might be worth taking the performance decrease of 40% in favor of simplified code? Let’s try and see what happens.
I’ve written a short test program, which calls 2 methods: passing by reference and passing by value. The code is available at https://github.com/larshp/return_by_value and the tests have been run on 750SP02.
With 1 million rows (around 1 GB) returned/exported 100 times, the averages are:
Using RETURNING does not seem to be 40% slower, but perhaps the base for the 40% is very small compared to the time required for populating the table, hmm
If pass-by-value copies the data, then the memory consumption needed for RETURNING should be twice that needed in EXPORTING. However, when looking at the memory consumption in the debugger the peak for RETURNING is the same as EXPORTING, but perhaps the actual kernel intermediate memory peak is not sent to the memory analysis tool.
Let’s try coping an internal table with 500.000 rows(500mb), and checking the memory usage,
lt_tab2 = lt_tab. BREAK-POINT.
2 identical tables with 500mb contents only takes 500mb, as it seems they share the same memory, i.e. only a shallow copy is made. Modifying the table contents:
READ TABLE lt_tab2 INDEX 1 ASSIGNING <ls_tab>. <ls_tab>-mandt = '123'. BREAK-POINT.
And each table occupies 500mb.
Internal Table Sharing
The concept of table sharing is described briefly in http://sapinsider.wispubs.com/Assets/Articles/2008/October/A-Developers-Guide-To-Protecting-Memory-Detect-And-Eliminate-Damaging-Memory-Leaks-With-ABAP-Memory which mentions “Table sharing also occurs when IMPORTING or EXPORTING parameters are passed by value”, but RETURNING is not mentioned.
Which provides a few additional hints.
As a special case table sharing is used for nested tables in RETURNING,
RETURNING can be used to pass large internal tables, if in doubt write a small test program to test the assumptions or try running the standard SAP code inspector check “Performance checks” -> “Poor parameter pass performance”. As everything else in ABAP, there are most likely some special cases which are not covered above.
Update: Also make sure to read the comments below, lots of valuable information