You are on page 1of 24

Performance Problems in ABAP Programs: How to Find Them

Performance Problems
in ABAP Programs:
How to Find Them
Werner Schwarz

Editor’s Note:
SAP Professional Journal has published ABAP performance articles on a
number of occasions. It is with particular pride that we present this special
two-part series. This first installment demonstrates how to use SAP’s tools for
performance analysis and describes how to identify the areas that dominate the
runtime of a poorly performing program. Although some of you may already be
familiar with using Performance Trace to analyze database accesses (an article
in the May/June 2002 issue covered this topic in detail), we think you will find
additional insights here, along with new material about using ABAP Runtime
Analysis, which is an invaluable tool for identifying critical sequences in your
ABAP code.
The second installment will profile the most frequently encountered causes of
Werner Schwarz joined SAP runtime maladies and offer suggestions for addressing those problems, with
Retail Solutions in October a focus on both database accesses and ABAP statements.
1998. Today, he is the Together these articles deliver a comprehensive approach to performance
development team contact optimization.
for all performance-related
issues concerning SAP’s
Lots of factors can give rise to sluggish execution of a transaction or a
Retail Industry Business
report. Sometimes there are general system problems. Sometimes users
Unit. Werner’s major use the program in a way it was not designed for. Sometimes the nature
tasks include information of the application and workload calls for parallel processing. And
rollout and support of his sometimes the source of the performance malady can be traced back to
colleagues regarding performance issues in your ABAP code.
performance during both
development and If you’ve ruled out deficiencies in the system setup, mishandling by
users, or the need for parallel processing, then you need to revisit your
maintenance.
code and see if the source of your runtime problems is lurking there.
But how do you approach such an exercise? I have found that most
(complete bio appears on page 62)

For site licenses and volume subscriptions, call 1-781-751-8699. 39


SAP Professional Journal May/June 2003

Is There a Bug Among Us?

Before you rush off on a search-and-destroy mission for bugs within your ABAP code, ask yourself the
following questions:
Does the performance problem occur only sporadically, even with small data volumes? And do
other transactions running at the same time also exhibit poor performance?
If the answers to these questions are yes, chances are good that the system setup is at fault. Ask your
system administrator to check for insufficient hardware, improper system configuration, database locks,
and system bottlenecks.
Are users misusing the program? Are they, for example, entering insufficient or unreasonable
restrictions in the data selection screen such that far more data is processed than necessary?
In this case, you should check if it is possible to optimize the user interface (using mandatory input
fields) or if you can perform some plausibility checks in your program to detect unreasonable input.
Finally, it can also make sense to retrain users.
Is the prolonged runtime simply caused by the amount of data that must be processed?
If this is the case, parallel processing and/or reducing the functionality of your program may be the
answer. In general, you should always ask yourself if the extent of the used functionality is really
needed and if the business benefits balance the required runtime.
If in reviewing your performance troubles you answered yes to any of the above questions, do not
proceed with the methodology I’m suggesting in this article. Address these issues first!

developers are more familiar and adept with the tools personal experiences and preferences, turned out to be
and procedures for identifying functional bugs than successful ones in many cases.
those associated with performance analysis. This
article aims to reduce, or even eliminate, that imbal- In the second part of this article, I will discuss
ance. Here, I offer an introduction to the use of the possible reasons for runtime problems. I have
SAP’s performance monitoring and tracing tools, and found that there are a few issues that tend to be
recommendations for wielding them. responsible for a majority of performance problems.
I will describe these issues in detail and also present
In the first part of this article, I will show you possible solutions.
how to determine whether your performance prob-
lems are caused by inefficient database accesses or by
awkward ABAP coding. I will also show you how to
deal with both types of performance problems. Of Performance Problems
course the procedure described in this article cannot Come in a Variety of Flavors
help you in all situations, as there are so many differ-
ent scenarios that can lead to performance problems. I know that most of you are familiar with the multi-
But the strategies I will describe, which are based on tier SAP architecture shown in Figure 1. There, you

40 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

Figure 1 The Standard SAP System Architecture

User ... User User User ... User User User ... User User

Instance 1 Instance 2 ... Instance n

Database

see one database, some instances where your ABAP Slow speeds and reduced bandwidth are obvi-
programs are executed in several work processes, and ously not ideal conditions for short response times.
a presentation layer (the client frontends) for display- Performance problems are bound to ensue. Perfor-
ing screens to the user and accepting user input. This mance problems are compounded when developers
is standard fare. Typically, the database is installed allow the amount of data sent between the application
on a database server along with an instance for server and presentation layer to be greater than it
administrative purposes and the enqueue processes. ought to be. Assume, for example, that a user wants
The other instances are installed on one or more to see a document that contains 3,000 line items. If
application servers.1 Each user uses a presentation the complete information on all 3,000 line items is
server (e.g., a PC with an SAP GUI), which is con- sent, the load on the frontend and the time required to
nected to an instance when logging in to the system. transfer the information can be considerable. Note,
however, that only about 20 lines can be displayed at
Network connections between the database and the same time and that the user has to scroll down to
application servers are typically fast. However, that’s see more information. In this scenario, the argument
not always the case with connections between the that scrolling would be faster with all the information
presentation layer and the application server, where downloaded to the frontend is not a sound one,
you often find slow WAN connections with high because users would have to wait up to several min-
latency times or small bandwidth. Let’s start our utes (an insufferably long time as far as they are
performance diagnosis dialog here. concerned) before the first screen could be displayed.
1
Here, it appears to be better to send only the informa-
One typically finds a single instance per application server, and that
is why the expressions “instance” and “application server” are often tion to the frontend for those 20 lines that can be
used interchangeably, even though they denote different things. displayed, despite the fact that data would have to be

For site licenses and volume subscriptions, call 1-781-751-8699. 41


SAP Professional Journal May/June 2003

exchanged between the frontend and application tables. This can cause a non-linear runtime (i.e.,
server with each scrolling. processing twice the number of work items in your
program leads to far more than doubling the runtime),
which can result in severe runtime problems with
growing data volumes. This problem can frequently
be solved — without changing the program design or
ü Tip the functionality — by simply applying the suitable
technical solution for the handling of the table
While this article focuses on finding performance and some smaller modifications. (This will be
problems in existing programs, let me offer you covered in the second installment of this two-part
this piece of advice for programs that you have article series.)
yet to develop: When it comes to performance,
your best defense is a good offense. You can
minimize the amount of data exchanged
Finally, all programs perform numerous accesses
between the application server and presentation to the database. This is another possible source for
layer through proper use of controls (e.g., trees, runtime problems, which should be considered thor-
tabstrips, and tables) and by not sending oughly. For example, selections that are not sup-
superfluous data to the frontend or performing ported by a suitable index can entail long (very long!)
superfluous roundtrips. runtimes. This not only potentially hampers the
running programs themselves, but is also an encum-
brance to all users, as they have only limited access
to the database if it is blocked by some long-running
selections.
Working our way down the layers of the multi-
tier architecture, the largest part of the load in a trans- So, now that you know that performance prob-
action is generally supposed to be performed in the lems can be lodged in a variety of places, where do
work processes on the application servers. Here, a you start your analysis when confronted with a
possible performance issue can be reading (and pro- poorly performing program? That’s what we will
cessing) too much data from the database or not examine next.
eliminating irrelevant data at the earliest opportunity.
Another critical point can be the unnecessary, identi-
cal repetition of actions. For example, lots of time
can be needlessly expended executing a function over
and over again for all the line items of a document, Pinpointing Performance
when, in fact, the function only needed to be per- Problems: Where to Begin
formed once per document. This mistake probably
stems from a lack of understanding that the function The first thing you need to do when trying to pinpoint
does not depend on the line information — or simply a performance problem in your code is determine
from carelessness. I see developers make this mis- whether the program’s runtime is dominated by time
take quite a bit with the implementation of certain spent on database requests or within the ABAP pro-
user exits. Bugs like that can cause a considerable gram. If the answer is database accesses, your perfor-
increase in runtime. Fortunately, they can be easily mance analysis will take you down one path; if the
identified with the appropriate monitoring tool. Later answer is ABAP execution, you’ll head down
in this article, I will show you how. another, as shown in Figure 2. As you can also see
in Figure 2, the determined path will prescribe which
Among the most treacherous pitfalls are those tool you will use (Performance Trace or ABAP
caused by sub-optimal handling of large internal Runtime Analysis) in the next steps of your analysis.

42 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

Figure 2 Is Runtime Dominated by Database Accesses or ABAP Execution?

@ Use transaction Statistics (STAD/STAT) or Process Overview (SM50).

? Is the database request time equal to or considerably larger than the CPU time?
@ Use Performance Trace (ST05) and ascertain which tables cause the highest load.

? Is the load caused by the use of an unsuitable execution plan?


Æ Check the execution plan of expensive statements using Explain SQL.

? Is the load caused by a large number of records/accesses?


Æ Check for identical selections or missing restrictions in the WHERE clause.

Æ Check for correct use of R/3 buffers.

? Is the CPU time equal to or considerably larger than the database request time?
@ Use ABAP Runtime Analysis (SE30) for further analysis and sort hitlist by net time.

? Are there modules with a high percentage of net time due to numerous calls?
Æ Reduce the number of calls if they are not justified.

? Are there modules with a high percentage of net time for only a few calls?
Æ Repeat analysis for this module including only accesses to internal tables.

? Long runtime cannot be linked to a few modules?


Æ Check program for possibilities to avoid unnecessary functionality.

There are usually two ways to make this determi-


ü Tip nation. One is to use statistical data from the system.
The other is to observe the program at runtime. In a
Before you attempt to isolate your performance moment, I will show you how to take advantage of
problem, verify that the suspected program has both options. Just one caveat before I do: If the
been recently executed. Otherwise, when
program you want to analyze for performance prob-
running the program, the runtime will be hard-
hit by the time it takes for database accesses to
lems takes hours to finish, it will not be feasible to
fill table and program buffers on the application conduct a performance analysis of the full execution
server, and hence distort the result. If possible, of the program. In cases such as this, see if it is
you should run the program once before possible to run the program with smaller data vol-
executing the run for the analysis. It is not umes and conduct your performance analysis over the
necessary to perform this “pre-run” with the abbreviated runtime. Often, this will give you the
full data volume — it is sufficient to process insights you need. In the descriptions that follow,
only one small document, or a small part of I will assume that you can use a test case with a
the workload, for example, to fill the program runtime that is short enough to perform a complete
buffer or table buffers.
analysis. If this is not the case, you will have to try
to analyze certain parts of the program, performing

For site licenses and volume subscriptions, call 1-781-751-8699. 43


SAP Professional Journal May/June 2003

Figure 3 Statistical Records Display (Transaction STAD)

your analysis in several smaller steps, or you will A performance analysis based on STAD/STAT
have to rely on observation and your wits. I will would proceed as follows:
offer a bit of help on this when I review the Process
Overview (transaction SM50) analysis in an upcom- 1. Run your program.
ing section.
2. Call transaction STAD/STAT and select the
relevant information.
Performance Analysis Option #1: Review the
Statistical Data 3. Examine the values in columns DB req. time
The R/3 system records statistical data for every and CPU time.
executed dialog step. This data contains (among
other things) information about the response time, In Figure 3, you see a screenshot with the output
the time required for database requests, and the from transaction STAD. Each dialog step that was
required CPU time (which can essentially be consid- executed on the system, and fulfills the restrictions
ered as the time that is spent in the ABAP code). you selected on the initial STAD screen, is displayed
You can access the statistical information using in a line of its own. You see the time of execution,
transaction STAT (in Release 4.5 or lower) or STAD the server where the dialog step was executed, the
(starting with Release 4.6). transaction and/or program it belongs to, the type of

44 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

work process (dialog, batch, update, etc.), the screen dialog step involving database operations (e.g., to
number of the dialog step, and the logical number of read or change records). Database calls are calls
the work process that executed this step. With this to the SAP database interface, which are either
information you can precisely identify the dialog already fulfilled by the R/3 table buffer or trans-
steps of interest. ferred to the database. The value of DB req.
time to a large extent depends on network run-
The important performance information appears times and the database server load.
in the columns described below. You can select the
information to be displayed using the Sel. fields In general, Response time is roughly the sum of
button in the application toolbar. For a performance CPU time and DB req. time. So:
analysis, we are interested in the Response time, CPU
time, and DB req. time columns (which are displayed • If DB req. time is considerably larger than
by default): CPU time, you should take this as a cue to focus
your attention on the database accesses. Proceed
• The Response time of a dialog step comprises with a detailed analysis of the database accesses
the time for the dialog request in the dispatcher using the Performance Trace tool, as indicated in
and in the work process, the processing time Figure 2.
itself, and the completion time of the dialog in the
dispatcher. Note that the time required for trans- • If CPU time is considerably larger than DB req.
ferring the data from the presentation server to the time, you should investigate the ABAP code.
dispatcher (and back) is not considered here. In Proceed with an analysis of the ABAP program
long-distance or low-performance networks, this code using the ABAP Runtime Analysis tool.
can lead to considerably longer “subjective”
response times, where the user’s impression of • If DB req. time and CPU time are almost equal,
the response time is longer than the time shown you must analyze both.
in this column.

For example, assume there is a very slow modem


connection between the user’s PC and the applica- ü Exercise Common Sense!
tion server, and that the transfer of the request to
• Always remember that statistical or derived
the application server takes 2 seconds, the process- data can be unreliable. For example, with
ing of the request takes 1 second, and the transfer long-running dialog programs, a value
of data back to the user’s PC takes 1 minute due to overflow of variables can occur, making the
the large amount of data. While STAD will show a derived time meaningless.
response time of 1 second for the dialog step, the
• Rely on the data only if it appears plausible
user’s impression will be that he had to wait over a (e.g., if the sum of CPU time and DB req.
minute to continue his work. time is not considerably larger than the
Response time).
• During execution of a dialog step, the application • If you are not sure whether the data is
server CPU is used for processing. In general, plausible, check to see if the data
the CPU time can be roughly identified as corresponds to the results of other
the time required for the execution of ABAP monitoring tools or to any observations
statements. you’ve made using the Process Overview
tool (transaction SM50).
• A certain amount of the time is required for a

For site licenses and volume subscriptions, call 1-781-751-8699. 45


SAP Professional Journal May/June 2003

Figure 4 Process Overview Screen (Transaction SM50)

Performance Analysis Option #2: Observe processed, you see which action is currently being
the Program with Process Overview (SM50) performed on which table.
The Process Overview tool (transaction SM50) pro- To use transaction SM50, proceed as follows:
vides a real-time view of what’s happening with your
program. You can see which process is currently 1. Run the program that you want to analyze.
handling your program and which database operation
is being performed on which table (if any). 2. Start a second session and open transaction SM50
to observe the execution of the program while
With the Process Overview (see Figure 4), you refreshing the display constantly.
can see the current state of all work processes on the
instance. Work processes are sorted by their logical You can identify the work process handling the
numbers, which are shown in column No. You can test program with the help of the User and Report
also see the work process type in column Ty. (e.g., columns. As you observe the test run, focus your
dialog, batch, update, etc.), the work process identi- attention on the Report, Action, and Table columns.
fier used by the operating system in column PID, and
the work process status in column Status. The status If you see that most of the processing time is
of most work processes is usually waiting. For a consumed by database operations (e.g., only one or a
performance analysis, we are interested in the work few long-running operations), then the long runtime
process that is currently executing the program under your program is exhibiting is likely caused by data-
examination (with a status of Running). For all run- base accesses. Alternatively, if the program is not
ning work processes, you see the execution time executing database operations for long periods of
(which is reset by certain operations, such as time (e.g., it remains in the same report without any
COMMIT WORK), the name of the report that is database operations), the long runtime is likely
executed, the client used, and the user who started the caused by sub-optimal ABAP coding. Either way,
program. If a statement accessing a database table is your path is clear — you need to perform an analysis

46 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

Figure 5 Performance Trace Process Overview

Session 1 Session 2 Session 1 Session 1

Start Run Stop List


Trace Program Trace Trace

1 2 3 4

of the database access activities, which I’ll review • Performance Trace records only the information
next, or you must perform an analysis of your coming from the work processes on the same
program’s ABAP routines, which I will cover after instance. Consequently, if you are using Remote
the database access discussion. Function Calls (RFCs) or asynchronous updates
in your program, the database accesses from these
modules will not be recorded if they are executed
on other instances.

Analyzing Database Access • Performance Trace can be used by only one


Activities with Performance Trace user at a time on each instance. Before using
the trace, please make sure that it is currently
If you found (or have assumed) that the long runtime switched off and not already in use (see the State
is caused by database accesses, use the Performance of trace section at the bottom of Figure 6).
Trace tool (transaction ST052) for further analysis.
With Performance Trace you can record all accesses
to the database coming from the instance. Figure 6 Performance Trace Start Screen
(Transaction ST05)
As you can see in Figure 5, you typically start
the trace in one session (1), start the program you
want to test in another session (2), switch off the trace
after the end of the program (3), and then analyze the
recorded data (4). Note that you can start the trace for
a program that is already running and switch it off
before the program’s end.

Figure 6 shows the start screen of the Perfor-


mance Trace tool. Before we examine the details of
using this tool, it is important to note the following
considerations:

2
The ST05 screenshots that appear in this article are based on Release
4.6C running on an Oracle database. If you are using a different
release or database, the screens you see may be different.

For site licenses and volume subscriptions, call 1-781-751-8699. 47


SAP Professional Journal May/June 2003

Figure 7 Narrow the Data to Be Traced

• The trace information is written to a file of a • Buffer trace covers all accesses to the table
fixed size. If the size limit of the file is reached, buffers on the instance.
the oldest data is overwritten. Consequently, it
is possible that the trace information of a long- For the analysis of database accesses, it is suffi-
running program will be incomplete and you will cient to activate just the SQL trace. The enqueue,
only see the most recent data. If this happens, a RFC, and buffer traces are useful for a performance
dialog box will inform you that parts of the trace analysis if you know (or suspect) that enqueue
file were overwritten. Data from older traces requests, RFCs, or accesses to the table buffers are
remain in the trace file only until the space is taking more time than they should.
required for new trace information.
When you start the trace, you can select whether
As you can see in Figure 6, there are four differ- or not you want to record data from all programs
ent trace modes for the performance trace: running under your user name on the instance (the
Trace on button) or if you want to define some filters
• SQL Trace covers all database accesses. (the Trace on with filter button).
• Enqueue trace covers all enqueue operations.
Figure 7 shows your options for narrowing the
• RFC Trace covers all RFC communications from data to be traced. You can select data from programs
and to the instance. running under another user’s name, select or exclude

48 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

Figure 8 Filter the Data to Be Displayed

certain tables, restrict the data to a specific work a very large trace file can be quite slow for certain
process (e.g., if you start the trace when the program functions, like determining identical selections, which
is already running), and so on. might be a consideration for you.

By pressing the Trace off button in the start Now let’s take a look at how to interpret all of
screen of ST05 (Figure 6) the trace is stopped. With this performance data.
Trace list, the recorded data is displayed for analysis.

Figure 8 shows your options for filtering the data


to be displayed. You can select the type of informa-
tion to be displayed (SQL, enqueue, RFC, buffer); Interpreting the Results
you can specify that you want to see only the basic of Your Performance Trace
list or extended information; you can select the time
period in which the data was recorded (by default it is Please be aware that the interpretation of the trace
the period of the last recorded trace); you can select information will be more effective if you are at least
the name of the user whose data should be displayed; somewhat familiar with the application and the busi-
and you can select the tables you want to see (or ness context, so that you can judge the usefulness of
not see). If a lot of data was recorded, a dialog box database accesses. The SQL trace can even help
might appear telling you that 5,000 trace records, for you discover superfluous functionality that you might
example, have been evaluated and asking if you want not be aware of. Eliminating such unnecessary func-
to evaluate more records. Generally, you do want to tions is always the best way to improve a program’s
evaluate all the data, but be aware that the analysis of performance.

For site licenses and volume subscriptions, call 1-781-751-8699. 49


SAP Professional Journal May/June 2003

Figure 9 Extended List Display of an SQL Trace

Take a look at Figure 9, which shows the • RC — The return code from the database
extended result of an SQL performance trace.
• Conn — The name of the database connection
The columns shown in Figure 9 (from left to
• Statement — The statement as it arrives at the
right) have the following meanings:
database
• HH:MM:SS.MS — The time at which the
operation was executed The shaded items are the ones that are important
for our performance discussion, and are the ones I
• Duration — The duration of the operation (in µs) would like to offer you a bit more detail on.
• Program — The name of the ABAP program
Sometimes the line that indicates the duration of
• ObjectName — The name of the affected table the operation is shaded in red, which means that the
duration time exceeds 100 ms. Note that this does
• Op. — The database operation not necessarily mean there is a performance problem
with this access, as you always have to take the num-
• Curs — The used cursor ber of processed records into consideration. For
• Array — The number of records that can be example, reading 1,000 records in 200 ms is a very
transferred in one step from the database good result, while reading only 5 records in 80 ms is
quite bad (as a rule of thumb, a processing time of
• Rec — The number of records that were read or up to 2-5 ms per record is okay, and thus need not
sent to the database (e.g., when inserting data) be a major concern to you at this time, even if it can

50 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

Figure 10 Details on the Number of Operations Performed in Each Step

potentially be faster). In the former case, where the Each database access from the program can
duration time is high although the response time per be split up into several database operations (e.g.,
record is not, you should still check whether this high PREPARE, OPEN, FETCH, etc.). For each of these
number of records is really required — perhaps you operations there is a separate line, which is identified
do not really need them all. by the Op. column. With the SQL performance trace,
operations look different for different databases. For
In the column Program, you see the name of the our purposes, it is not necessary to consider these
ABAP program where the access was coming from. operations in detail; you can simply sum up the times
In order to navigate to the code sequence belonging to for the single operations concerning an access or
it, place the cursor on the line with the statement in consider only the largest value.
question and select the ABAP display button ( ),
Goto → ABAP display, or F5. Please make sure that
the cursor is not located on a FETCH operation, as The column Rec tells you how many database
navigation to the source code — like some other records were read and transferred to the application
functions — is not possible for this operation. server in one step (operation FETCH). Sometimes
the result of the query consists of more records than
The column ObjectName contains the name of can be transferred in one step. In this case, you
the database table affected. If you want to see some would see several lines with repeated FETCH opera-
information from the DDIC (the data dictionary) for a tions, as you can see in the example shown in
particular table, place the cursor on a line containing Figure 10.
that table and select the DDIC info button, Goto →
DDIC info, or F6. In this example, each FETCH transferred 1,625

For site licenses and volume subscriptions, call 1-781-751-8699. 51


SAP Professional Journal May/June 2003

Figure 11 Summary of the Trace

records in one step, but this had to be repeated until is an understanding of which accesses cause the high-
all records (50,000 in this case) were transferred. For est load. It’s only logical that this is where you con-
INSERT, UPDATE, or DELETE operations, this centrate your efforts.
column tells you how many records were inserted,
updated, or deleted. In order to identify which tables are excessively
accessed, Performance Trace enables you to aggregate
In the final column (Statement) you see the all accesses by the names of the tables. By summing
statement as it was handed over to the database. up all the request times, you can see which accesses
This usually looks a little different from the original to which database tables are causing the highest
ABAP statement because it was transformed by database loads.
the Open SQL layer on the instance. The complete
statement is displayed when you place the cursor The menu item Goto → Summary provides
on the line with the statement in question and select you with a shortened version of the SQL perfor-
the details button ( ), Edit → Details, or F2. mance trace. After activating the Summarize
button, you will see a list with the information
aggregated for each table (after confirming the
checks in the resulting dialog box). Figure 11
Ascertaining Which Database Accesses displays a list that is already sorted by time to
Cause the Highest Load identify the database tables with the highest loads.
These loads might be caused by the number of
Central to any database access performance analysis accesses, the amount of read data, or by expensive

52 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

Indexes — A Quick Overview

A good way to think of an index is to envision a phone book. If you are looking for a specific phone
number, you need not check the complete phone book from end-to-end because entries are sorted by
city, last name, first name, and street. You can find a phone number (i.e., a searched record) very
quickly if you know the address and the name of the person you want to call. Even if you don’t know
the street address, there remain only a few entries. The time you need to find the number is only
marginally dependent on the total number of entries (i.e., the size of the database table).

However, if you want to use the index, you must know the values of the index fields of the searched
record, or at least the values of the first few fields. If you don’t know the location, and only know the
last name, first name, and birthday of the person you want to call, then a standard phone book won’t
help. You would need an additional phone book (i.e., another index) where the entries are sorted by
last name, first name, and birthday. Thus it is useful for large tables to have indexes for all types of
frequently used accesses. Keep in mind that while additional indexes will accelerate accesses, actions
that modify the database table (e.g., INSERT, DELETE, UPDATE) will suffer performance degradation,
since these actions require an update of all indexes.

statements. You should first focus your analysis on WHERE clause. Obviously, the higher the num-
the accesses to these tables. ber of entries in the table, the longer this proce-
dure takes.3

• Use an index that points directly to those records


with specific value combinations for the index
ü Tip fields. This can substantially reduce the number
of records to be read. (See also the above sidebar
You can also use the “Statement summary” “Indexes — A Quick Overview.”)
function (menu item Goto → Statement summary)
to get an indication of which database accesses
should be analyzed in detail. For each selection in the SQL trace, you can
check the execution plan that is being used by the
database. Simply place the cursor on the line
containing the statement in question4 and then select
the button, Trace → Explain SQL, or F9.
Examine the “Execution Plan” The look of the next screen is heavily dependent on
Used by the Database the specific database you use, so there are several
different possibilities for the display you might see.
For each access, the database determines the best way In general, you will see the statement as it was
to handle the request. There are basically two options
for this database “execution plan”:
3
Due to a block-wise reading, several records can be fetched in one
• Perform a full table scan where the database step, so this execution plan is ideal for smaller tables or if the result set
consists of a large part of all records in the table (about 10% or more).
simply reads all records from the table and then
picks the ones that meet the conditions from the 4
This must not be a FETCH operation!

For site licenses and volume subscriptions, call 1-781-751-8699. 53


SAP Professional Journal May/June 2003

handed over to the database and the execution plan Figure 12 Example Execution Plans
(note that for some databases, you might have to
activate another button to see the execution plan).
Then you can decide whether or not the selected
execution plan is acceptable.

Figure 12 shows a few example execution plans


as they are displayed for an Oracle database. In the
first of these execution plans, you see a Full Table
Scan. In the second, you see an Index Unique Scan, Full Table Scan
which means that all index fields were specified with
“=” in the WHERE clause. The third execution plan
is an Index Range Scan, which tells you that not all
index fields were specified with “=” in the WHERE
clause, requiring the database to read several index
entries to determine the result set.

The execution plan also tells you how the data-


base handles a selection using a JOIN command. A
JOIN is used to access combined information from
multiple tables. When using a JOIN, you must con-
sider the way the database reads and uses the infor-
mation from these tables. Usually you expect the
database to perform a “nested” JOIN, which means Index Unique Scan
that the database first reads the information from
one table according to the restrictions in the WHERE
clause, starting with the table with the “best” restric-
tion. Using the result set, and considering the JOIN
condition, the next table is accessed to read further
data, and so on. In this way, the number of records
to be read from the different tables should progres-
sively decrease.

But the database might decide to use a “merge”


JOIN, where the records from the affected tables
are read independently and only restrictions in the
WHERE clause are considered. In a second step, the
result sets are merged according to the JOIN condi-
tion. Obviously, this can cause very long runtimes,
especially if large tables are affected that have no Index Range Scan
suitable index available. In such a case, it may be
beneficial to replace the JOIN statement by two or
more selections on each table, using the FOR ALL
ENTRIES clause to emulate the nested JOIN. You
can also use this trick if the database uses a nested
JOIN but starts with the wrong table.

54 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

Figure 13 Example Identical Selects

Finding Identical Selects menu item Goto → Identical Selects gives you a
list of all identical selections in the trace. Selections
When analyzing an SQL performance trace, you will
are considered identical if they perform the same
quite often find the same database accesses being
query on the same table(s) with the same values
performed repeatedly within a program or transaction.
for the fields in the WHERE clause. Figure 13
There are only very rare cases where this is really
shows an example.
necessary. Usually it is sufficient to perform a data-
base query once and keep the results in the program
context for future use. Be aware that two statements are considered iden-
tical selections only if both the database statements —
With the Performance Trace tool, it is easy to find compared as strings — and all the values for the fields
these identical selections (i.e., “Identical Selects”), in the WHERE clause are the same. There might be
which are superfluous in most cases. Activating the several other statements that read the same record and

For site licenses and volume subscriptions, call 1-781-751-8699. 55


SAP Professional Journal May/June 2003

Listing 1: Example Selections on Table MARC

1 SELECT * FROM MARC WHERE "MANDT" = '800' AND "MATNR" = 'ABCD'


AND "WERKS" = '3000'
2 SELECT * FROM MARC WHERE "MANDT" = '800' AND "MATNR" = 'ABCD'
AND "WERKS" = '3001'
3 SELECT * FROM MARC WHERE "MANDT" = '800' AND "WERKS" = '3000'
AND "MATNR" = 'ABCD'
4 SELECT * FROM MARC WHERE "MANDT" = '800' AND "MATNR" = 'ABCD'

are not considered identical. For example, take a look Analysis of ABAP Routines
at the selections shown in Listing 1.
Now that you are aware of the problems that can be
If these statements were in the trace, they would caused by the database, it’s time to turn our attention
not be rated as identical for the following reasons: to the ABAP program runtime. As indicated back in
Figure 2, you should use the ABAP Runtime Analy-
• Statement 2 is nearly the same as statement 1, but sis tool for further investigation if the major part of
the value of the searched record’s WERKS field is the runtime is spent within the ABAP program itself.
3001 (rather than 3000). Although this is the preferred method, as it provides
you with the most accurate results, you can also try a
• Statement 3 reads exactly the same data as more heuristic approach (the “Monte Carlo” method
statement 1, but the sequence of the fields in described in the sidebar on the next page) to identify
the WHERE clause is different, so the string the critical code sequences.
comparison considers these statements different.

• The result set of statement 4 already contains the Using the ABAP Runtime Analysis Tool
data that is read in statements 1-3, as there is no (Transaction SE30)
additional restriction with respect to the WERKS
field. So, it would be sufficient to retrieve the The ABAP Runtime Analysis tool was considerably
records from statement 4’s result set and omit improved with Release 4.6, at which time it became a
statements 1-3. Of course, this cannot be far more usable tool than it had been previously. The
detected by the search for identical selections most striking improvement is in the way the tool can
in the performance trace. be used to configure the traced information, espe-
cially with regard to aggregating the data. This sig-
The identical selection results provide you with a nificantly reduces the size of the trace information,
list of statements that you should check during your which in turn avoids the occurrence of short dumps
analysis. However, as you have just seen, there due to trace file overflow and reduces the time needed
might be more superfluous selections that are not to evaluate the trace. There are still some restrictions
detected automatically by Performance Trace. In the — no tracing of update processes, RFCs, or batch
second, and concluding, article of this series, I will jobs, except in a parallel session, sporadic problems
show you how to deal with identical selections and on certain operating systems — but they will be
how to avoid the associated performance penalties. mostly eliminated with the R/3 Enterprise release.

56 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

The “Monte Carlo” Method

With this heuristic approach, you do not perform a detailed trace for the whole program. Instead, you
monitor the program with the Process Overview tool (transaction SM50), and when you find the process
remaining in the same program for a long time, you simply stop the program with the debugger (menu
item Program/mode → Program → Debugging). Analyze the current call stack, and in particular search
for a loop over large internal tables. If you do this repeatedly, and you see that the process frequently
stops in the same loop on the same internal table, it is very likely that the reason for the extended
runtime lies in the processing of this loop.

You may uncover the reason for the problem just by investigating the code in this area (the description in
the second installment of this series will help you a lot with this) or by using the ABAP Runtime Analysis
(transaction SE30) for a detailed analysis of this code area.

Figure 14 ABAP Runtime Analysis Initial Screen

Although I assume that you are familiar with this After starting the ABAP Runtime Analysis (see
tool, allow me to offer a short description of how to Figure 14) via transaction SE30, you should first
use it for our purposes here (on a 4.6 system). configure the restriction variant you want to use.

For site licenses and volume subscriptions, call 1-781-751-8699. 57


SAP Professional Journal May/June 2003

Figure 15 The “Program (parts)” Tab Figure 16 The “Statements” Tab

For the first analysis, it is usually sufficient to


use the DEFAULT variant. The DEFAULT variant
traces the complete transaction, considers almost all
statements and modularization units,5 and aggregates
the data. Aggregation means that the times for local
module calls are summed up and you will get one
entry for each module showing the total time and
• Handling of internal tables is the key to the prob-
number of calls.
lem in many cases. So on the Statements tab,
activate the checkboxes Read operations and
For a more detailed analysis of a single module or
Change operations for internal tables, as shown
a certain code sequence — which is usually the sec-
in Figure 16.
ond step of a performance analysis — you should
define a new variant:
• Usually, aggregated data gives you sufficient
information for your analysis. If, however, you
• To trace only a specific function module/form
still need more detailed information, switch off
routine/method, enter its name on the Program
the aggregation by using the appropriate radio
(parts) tab — in Figure 15, form PARALLEL
button on the Duratn/type tab (see Figure 17).
in program ZDS400_APDX_LZA. To trace
only a certain code sequence (e.g., only
After configuring and then selecting the new
some statements inside of a module), activate
variant, start the test run. You can add a short
the checkbox Particular units and mark the
description of your test case in the Comment field on
start and the end of this sequence with
the main screen to distinguish between the trace files
breakpoints. Later, when hitting the break-
from different test runs. Depending on whether you
points at execution, switch the tracing on and
want to trace a program or a transaction, select the
off accordingly using the menu item System →
appropriate radio button in the In current session
Utilities → Runtime Analysis → Switch on/off
area. Enter the name of the transaction or program to
inside of the debugger.
be tested in the corresponding input field and click
the Execute button. The program/transaction starts
5
Except accesses to internal tables, which would be too detailed for the and the data records are collected according to your
first analysis. selected variant. When the program/transaction is

58 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

Figure 17 The “Duratn/type” Tab Now that the information records are collected,
click the Analyze button to start the analysis.

ü Tip
Sometimes you will see an error message in the
status line saying that there is no data displayed
in the “Performance file” area or that the file
size is zero. Nevertheless, you should check if
there is a trace file (using the button “Other
file…”) that can be used. Look at the trace
information and assess whether the information
is plausible. If it is, use it for your analysis.

complete, return to the ABAP Runtime Analysis by


pressing F3 or using the back icon ( ). Interpreting the Trace Information
The first screen of the analysis — which you can see
The ABAP Runtime Analysis display will show in Figure 19 — shows how the elapsed time is dis-
you information about the recorded trace file in the tributed among three categories:
area Performance file (see Figure 18).
• ABAP — The time spent in the ABAP program

• Database — The time spent in the database


Figure 18 The ABAP Runtime Analysis
Display After the Program Executes • R/3 System — The time spent solely on system
issues

Figure 19 Overview of the Runtime


Analysis Results

For site licenses and volume subscriptions, call 1-781-751-8699. 59


SAP Professional Journal May/June 2003

Figure 20 The Hitlist Sorted by Net Time

The time spent in ABAP should have the highest will find one or more icons for displaying further
percentage. If the highest percentage is spent on information on the call hierarchy, accessed database
database accesses, it may be more useful to use the tables, and internal tables, for example. In the
SQL performance trace for analysis (see the earlier discussion here, I will focus on the hitlist button
discussion in the section “Analyzing Database Access ( ),6 which is always available, regardless of the
Activities with Performance Trace”). If you find a variant’s settings.
major part of the runtime was spent in the R/3 sys-
tem, this may indicate problems when recording the In the hitlist (Figure 20) you will find informa-
trace information, and often the data cannot be used tion on each function module, form routine, and
for a helpful analysis.

Depending on your variant’s settings (i.e., 6


Instead of this button you can also press F5 or use the menu item
whether the information is aggregated or not), you Goto → Hitlist → Standard.

60 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.
Performance Problems in ABAP Programs: How to Find Them

method that was called during the run. As you can In the second installment of this two-part article
see, the following information is displayed: series, I will discuss in detail performance problems
• No. — The number of times the module was that are caused by the sub-optimal use of internal
called tables and outline possible solutions.
• Gross — The gross time spent in this module,
including the time spent in modules called from
within this module
Conclusion
• Net — The net time spent solely in this module,
not including the time spent in modules called In our work with SAP R/3 installations, my col-
from within this module7 leagues and I have found a number of common
performance pitfalls. Sometimes there is a weak
In order to find the most critical modules, you design, which makes a correction quite expensive —
should sort the list by net time. If you find some at a widespread modification of the program would be
the top of the list that are consuming a high percent- necessary instead of only a local optimization. But
age of the total net time (as is the case with the first sometimes the extended runtime is simply caused by
module listed in Figure 20), these are good candidates the way functionality was implemented — i.e., not
for optimization. all relevant performance aspects were considered.

If one module consumes a large percentage of the Whatever the cause of your program’s perfor-
runtime, focus on this module in the next step of your mance troubles, optimizing the runtime of the appli-
investigation. I recommend defining a new restric- cation requires that you first find out where the major
tion variant for a thorough analysis of this module, part of the runtime is spent. It just doesn’t make
including the use of internal tables. Then repeat the sense to focus your tuning efforts on the parts of the
analysis using this new variant. In many cases the program that require relatively little runtime. There
hitlist (sorted by net time) shows operations on inter- is probably one exception to this: to achieve a satisfy-
nal tables at the top of the list. ing result if no single hotspot is found, you may be
forced to optimize the program by tuning several
parts, even if separately they are responsible for only
small fractions of the runtime.
ü Note!
If no such modules exist, tuning the transaction is With the help of SAP’s performance tools,
not that easy and likely cannot be achieved by you can easily identify the critical actions or code
local technical optimizations. Instead, check sequences. As a first step, you have to decide where
the complete order of events in the program — to optimize: the database accesses or the ABAP cod-
analyzing the hitlist sorted by gross time can give ing of the program. Your decision will be driven by
you a clue as to which modules/functions require examining the statistical data of the program (using
the most time and where an optimization can pay transactions STAT/STAD) or by observing the pro-
off. But this is heavily dependent on the specific
gram in the Process Overview (transaction SM50).
program or transaction, so unfortunately in this
To analyze database accesses, use Performance
case I cannot give you “one-size-fits-all” advice
on how to proceed. Trace (transaction ST05), and for the analysis of
an ABAP program, use ABAP Runtime Analysis
(transaction SE30).

7
Depending on the results of your analysis, you
If the module does not call any other modules, the net time is equal to
the gross time. can then implement the necessary corrections. In the

For site licenses and volume subscriptions, call 1-781-751-8699. 61


SAP Professional Journal May/June 2003

next installment of this two-part series — “Perfor-


mance Problems in ABAP Programs: How to Fix Werner Schwarz joined SAP Retail Solutions
Them” — I present common performance bugs and in October 1998 after working as a developer
recommended solutions. After applying a correction, at two other IT companies. Today, he is the
you should run and analyze the program again in
development team contact for all performance-
order to verify that the revision produces the desired
result. You may also observe newly visible runtime related issues concerning IBU Retail (Industry
effects that you could not see before — if you are not Business Unit Retail). Werner’s major tasks
satisfied with your program speed, continue tuning it include information rollout and support of his
by focusing on these new effects. colleagues regarding performance during both
development and maintenance. He can be reached
at werner.schwarz@sap.com.

62 www.SAPpro.com ©2003 SAP Professional Journal. Reproduction prohibited. All rights reserved.

You might also like