Skip to main content
ABAP

Dev Tip: Using the REDUCE operator instead of SUM will improve the performance of your ABAP code.

Mike Berg Mike Berg, Senior Developer 2 min read

In case you’ve missed our dev tips in past weeks, we will be posting them in the blog moving forward. To sign up and get your dev tips delivered to your inbox each week, click here!

Tip of the Week

Using the REDUCE operator instead of SUM will improve the performance of your ABAP code.

In the development world, time matters. Too often we focus on development time rather than program runtime. Deadlines certainly matter, but if your program performs so poorly that it’s unusable, the project will be a failure. This week’s tip will help you extract column totals from internal tables in a more efficient manner.

For years, ABAPers were required to loop through internal tables and use the SUM operator to get column totals. Starting with ABAP 7.40 SP08, a new operator called REDUCE was added.

The setup:
I created an internal table of student names and grades. You can do this however you’d like – I used another new ABAP 7.40 trick – the FOR loop.

ABAP code filling t_grades1 with a VALUE FOR loop from 1 to 100, name Student plus i, grade i

This is the structure of internal table t_grades1:

ABAP TYPES definition ty_grades with fields name TYPE char20 and grade TYPE i

I now have an internal table of 100 students with grades from 1 to 100 to play with.

Debugger table contents of T_GRADES1, 100 rows, showing Student1 to Student7 with grades 1 to 7

To prove out the benefit of REDUCE over SUM, I created two FORMs. One contains the code for SUM and the other for REDUCE.

ABAP FORM f_sum_via_loop that loops over t_grades1 and uses SUM inside AT LAST

ABAP FORM f_sum_via_reduce using REDUCE i( INIT x = 0 FOR wa IN t_grades1 NEXT x = x + wa-grade )

Just as a side note, doesn’t the REDUCE code look cooler?

Let’s test this out though. Is SUM or REDUCE better?

Runtime analysis: F_SUM_VIA_LOOP 43 microseconds, F_SUM_VIA_REDUCE 23 microseconds

Ok, REDUCE wins, but 20 microseconds isn’t much. Let’s up the record count from 100 to 1000.

Runtime analysis: F_SUM_VIA_LOOP 340 microseconds, F_SUM_VIA_REDUCE 207 microseconds

Now we’re seeing the difference. Let’s up it to 50000 records!

Runtime analysis: F_SUM_VIA_LOOP 16,504 microseconds, F_SUM_VIA_REDUCE 9,947 microseconds

Honestly speaking, 6500 microseconds is less time than it takes to blink your eye. In the computing world, we can’t think in terms of one iteration. What if you were able to save this execution time 10 times in a program and that program was executed hundreds of times per day? The cost savings add up quickly!

If you have an interest in viewing similar content, visit our blog, here.

View our LinkedIn, here.

Share