Performance q: decls in loops

Performance question: declarations in loops
I'm wondering if there is any performance difference in the following two scenarios, discounting any special exceptions for special optimizing compilers etc -- just imagine a generic situation with the following two scenarios:
Scenario 1: declaration outside the loop
void someMethod() {
  String s;
  while (x != 0) {
    if (someCondition) {
      s = new String("SomeString");
Scenario 2: declaration inside the loop
void someMethod() {
  while (x != 0) {
    String s;
    if (someCondition) {
      s = new String("SomeString");
}Are there any design-related reasons to choose Scenario 2?

In scenario 2 the VM has to repeatedly re-allocate
memory for the object referece s (never mind what it
points to), and repeatedly garbage collect it.Thanks -- that answers my question and confirms what I had been thinking. I adopted this example code from page 640 of "Thinking In Java 2nd Edition" (Eckel), and was posting to find out whether or not there was some reason that he had written it that way. (If anyone is curious I have pasted the code at the end of this post, the book is freely downloadable at http://www.mindview.net/)
also the line
s = new String("SomeString");
is nearly as wastefull as
s = new String(new String("SomeString"))
It should be simplified to
s = "SomeString";Yeah, I read this in "Effective Java" by Bloch. Thanks for pointing it out though in case I didn't know that.
Are there any design-related reasons to choose
Scenario 2?
Maybe if you're testing performace of the garbage
collector or VM.LOL.
Here's the code, for the curious:
//: c11:WordCount.java
// From 'Thinking in Java, 2nd ed.' by Bruce Eckel
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
// Counts words from a file, outputs
// results in sorted form.
import java.io.*;
import java.util.*;
class Counter {
  private int i = 1;
  int read() { return i; }
  void increment() { i++; }
public class WordCount {
  private FileReader file;
  private StreamTokenizer st;
  // A TreeMap keeps keys in sorted order:
  private TreeMap counts = new TreeMap();
  WordCount(String filename)
    throws FileNotFoundException {
    try {
      file = new FileReader(filename);
      st = new StreamTokenizer(
        new BufferedReader(file));
      st.ordinaryChar('.');
      st.ordinaryChar('-');
    } catch(FileNotFoundException e) {
      System.err.println(
        "Could not open " + filename);
      throw e;
  void cleanup() {
    try {
      file.close();
    } catch(IOException e) {
      System.err.println(
        "file.close() unsuccessful");
  void countWords() {
    try {
      while(st.nextToken() !=
        StreamTokenizer.TT_EOF) {
        String s;
        switch(st.ttype) {
          case StreamTokenizer.TT_EOL:
            s = new String("EOL");
            break;
          case StreamTokenizer.TT_NUMBER:
            s = Double.toString(st.nval);
            break;
          case StreamTokenizer.TT_WORD:
            s = st.sval; // Already a String
            break;
          default: // single character in ttype
            s = String.valueOf((char)st.ttype);
        if(counts.containsKey(s))
          ((Counter)counts.get(s)).increment();
        else
          counts.put(s, new Counter());
    } catch(IOException e) {
      System.err.println(
        "st.nextToken() unsuccessful");
  Collection values() {
    return counts.values();
  Set keySet() { return counts.keySet(); }
  Counter getCounter(String s) {
    return (Counter)counts.get(s);
  public static void main(String[] args)
  throws FileNotFoundException {
    WordCount wc =
      new WordCount(args[0]);
    wc.countWords();
    Iterator keys = wc.keySet().iterator();
    while(keys.hasNext()) {
      String key = (String)keys.next();
      System.out.println(key + ": "
               + wc.getCounter(key).read());
    wc.cleanup();
} ///:~

Similar Messages

  • Performance enhancement for parallel loops

    Hi,
      I have performance problem for the following parallel loops.Please help me solve this to improve performance of report,urgently.
    LOOP AT xt_git_ekpo INTO lv_wa_ekpo.
    lv_wa_final-afnam     = lv_wa_ekpo-afnam.
    LOOP at xt_git_ekkn into lv_wa_ekkn  where ebeln = lv_wa_ekpo-ebeln
    and ebelp = lv_wa_ekpo-ebelp.
    lv_wa_final-meins     = lv_wa_ekpo-meins.
    READ TABLE xt_git_ekko INTO lv_wa_ekko
                                    WITH KEY ebeln = lv_wa_ekpo-ebeln
                                    BINARY SEARCH.
          IF sy-subrc IS INITIAL.
            lv_wa_final-ebeln     = lv_wa_ekko-ebeln.
            lv_wa_final-ebelp     = lv_wa_ekpo-ebelp.
            lv_wa_final-txz01     = lv_wa_ekpo-txz01.
            lv_wa_final-aedat     = lv_wa_ekko-aedat.
    READ TABLE xt_git_lfa1 INTO lv_wa_lfa1
                                          WITH KEY lifnr = lv_wa_ekko-lifnr
                                          BINARY SEARCH.
            IF sy-subrc IS INITIAL.
              lv_wa_final-lifnr = lv_wa_lfa1-lifnr.
              lv_wa_final-name1 = lv_wa_lfa1-name1.
            ENDIF.
         LOOP AT xt_git_ekbe INTO lv_wa_ekbe WHERE   ebeln      =   lv_wa_ekpo-ebeln
    AND  ebelp = lv_wa_ekpo-ebelp.
    waiting for quick reply.

    Hi
    U can use SORTED TABLE instead of STANDARD TABLE:
    DATA: xt_git_ekkn TYPE SORTED TABLE OF EKKN WITH NON-UNIQUE KEY EBELN EBELP,
              xt_git_ekbe  TYPE SORTED TABLE OF EKBE WITH NON-UNIQUE KEY EBELN EBELP.
    LOOP AT xt_git_ekpo INTO lv_wa_ekpo.
        lv_wa_final-afnam = lv_wa_ekpo-afnam.
        LOOP at xt_git_ekkn into lv_wa_ekkn where ebeln = lv_wa_ekpo-ebeln
                                                                  and ebelp = lv_wa_ekpo-ebelp.
            lv_wa_final-meins = lv_wa_ekpo-meins.
            READ TABLE xt_git_ekko INTO lv_wa_ekko WITH KEY ebeln = lv_wa_ekpo-ebeln
                                                                                    BINARY SEARCH.
            IF sy-subrc IS INITIAL.
              lv_wa_final-ebeln = lv_wa_ekko-ebeln.
              lv_wa_final-ebelp = lv_wa_ekpo-ebelp.
              lv_wa_final-txz01 = lv_wa_ekpo-txz01.
              lv_wa_final-aedat = lv_wa_ekko-aedat.
              READ TABLE xt_git_lfa1 INTO lv_wa_lfa1 WITH KEY lifnr = lv_wa_ekko-lifnr
                                                                                    BINARY SEARCH.
              IF sy-subrc IS INITIAL.
                 lv_wa_final-lifnr = lv_wa_lfa1-lifnr.
                 lv_wa_final-name1 = lv_wa_lfa1-name1.
             ENDIF.
             LOOP AT xt_git_ekbe INTO lv_wa_ekbe WHERE ebeln = lv_wa_ekpo-ebeln
                                                                             AND ebelp = lv_wa_ekpo-ebelp.
    Anyway u should considere to upload in the internal table only the record of the current document, in this case u need to insert the SELECT into the loop:
    SORT  xt_git_ekpo by EBELN EBELP.
    LOOP AT xt_git_ekpo INTO lv_wa_ekpo.
        lv_wa_final-afnam = lv_wa_ekpo-afnam.
       IF lv_wa_ekkn-EBELN <>  lv_wa_ekpo-EBELN.
         SELECT * FROM EKKN INTO TABLE xt_git_ekkn WHERE EBELN = lv_wa_ekpo-EBELN.
         SELECT * FROM EKBE INTO TABLE xt_git_ekbe WHERE EBELN = lv_wa_ekpo-EBELN.
       ENDIF.
        LOOP at xt_git_ekkn into lv_wa_ekkn where ebelp = lv_wa_ekpo-ebelp.
            lv_wa_final-meins = lv_wa_ekpo-meins.
            READ TABLE xt_git_ekko INTO lv_wa_ekko WITH KEY ebeln = lv_wa_ekpo-ebeln
                                                                                    BINARY SEARCH.
            IF sy-subrc IS INITIAL.
              lv_wa_final-ebeln = lv_wa_ekko-ebeln.
              lv_wa_final-ebelp = lv_wa_ekpo-ebelp.
              lv_wa_final-txz01 = lv_wa_ekpo-txz01.
              lv_wa_final-aedat = lv_wa_ekko-aedat.
              READ TABLE xt_git_lfa1 INTO lv_wa_lfa1 WITH KEY lifnr = lv_wa_ekko-lifnr
                                                                                    BINARY SEARCH.
              IF sy-subrc IS INITIAL.
                 lv_wa_final-lifnr = lv_wa_lfa1-lifnr.
                 lv_wa_final-name1 = lv_wa_lfa1-name1.
             ENDIF.
             LOOP AT xt_git_ekbe INTO lv_wa_ekbe WHERE ebelp = lv_wa_ekpo-ebelp.
    In my experience (for a very large number of records) this second solution was faster than the first one:
    - Using the first solution (upload all data in internal table and use sorted table): my job takes 2/3 days
    - Using the second solution: my job takes 1 hour.
    Max

  • Avoiding performance issue due to loop within loop on internal tables

    Hi Experts,
                    I have a requirement where in i want to check whether each of the programs stored in one internal table are called from any of the programs stored in another internal table. In this case i am looping on two internal tables (Loop within a loop) which is causing a major performance issue. Program is running very very slow.
    Can any one advise how to resolve this performance issue so that program runs faster.
    Thanks in advance.
    Regards,
    Chetan.

    Forget the parallel cursur stuff, it is much to complicated for general usage and helps nearly nothing. I will publish a blog in the next days where this is shown in detail.
    Loop on loop is no problem if the inner table is a hashed or sorted table.
    If it must be a standard table, then you must make a bit more effort and faciliate a binary search (read binary search / loop from index exit)
    see here the exact coding Measurements on internal tables: Reads and Loops:
    /people/siegfried.boes/blog/2007/09/12/runtimes-of-reads-and-loops-on-internal-tables
    And don't forget, the other table must not be sorted, the loop reaches anyway every line. The parallel cursor requires both tables to be sorted. The additional sort
    consumes nearly the whole advantage of the parallel cursor compared to the simple but good loop in loop solutions.
    Siegfried

  • Performance Issue of the loop

    I have an ITAB which contains PO header details and another ITAB which has PO Item details. Now  I need to to take this info. in a single ITAB and send it to some FM. Which will be the best  way to do this ?
    When I do,
    Loop at it_header into wa_header.
    wa_new-BUKRS = wa_heaeder-bukrs.
    wa_new-LIFNR = wa_heaeder-LIFNR.
    wa_new-BSTYP = wa_heaeder-BSTYP.
    wa_new-BSAKZ = wa_heaeder-BSAKZ.
    Loop at it_item into wa_item where ebeln = wa_header-ebeln.
    wa_new-werks = wa_item-werks.
    wa_new-MATNR = wa_item-MATNR.
    wa_new-AEDAT = wa_item-AEDAT.
    wa_new-MENGE = wa_item-MENGE.
    wa_new-MEINS = wa_item-MEINS.
    wa_new-IDNLF = wa_item-IDNLF.
    append wa_new to it_new.
    appended = 'X'.
    endloop.
    if appended ne 'X'.
    append wa_new to it_new.
    endif.
    clear wa_new.
    Endloop.
    This code consumes a lot of time since I have a huge amount of data.Could you please suggest  some other method?

    Hi,
    You haven't explained how you are getting the data in the tables.If you only are selecting it , may be you can select the data at a time by using a join into the itab it_new directly.
    If you are getting this data from somewhere else , we cant do anything on the select. In that case you can try using the parallel cursor method.
    Before using this technique , you have to make sure that it_item is a sub table of it_header. That means, all the EBELN's in it_item should be there in it_header  also. Since this is a PO info., I assume that the condition is satisfied.
    Then try this code instead of your Loop.
    Sort it_header by ebeln.
    sort it_item by ebeln.
    LOOP AT IT_HEADER INTO WA_HEADER.
    wa_new-BUKRS = wa_heaeder-bukrs.
    wa_new-LIFNR = wa_heaeder-LIFNR.
    wa_new-BSTYP = wa_heaeder-BSTYP.
    wa_new-BSAKZ = wa_heaeder-BSAKZ.
    LOOP AT IT_ITEM INTO WA_ITEM FROM INDEX.
    IF WA_ITEM-EBELN NE WA_HEADER-EBELN.
    INDEX = SY_TABIX.
    EXIT.     
    ENDIF.
    wa_new-werks = wa_item-werks.
    wa_new-MATNR = wa_item-MATNR.
    wa_new-AEDAT = wa_item-AEDAT.
    wa_new-MENGE = wa_item-MENGE.
    wa_new-MEINS = wa_item-MEINS.
    wa_new-IDNLF = wa_item-IDNLF.
    append wa_new to it_new.
    appended = 'X'.
    ENDLOOP.
    if appended ne 'X'.
    append wa_new to it_new.
    endif.
    ENDLOOP.
    Try this code instead..
    If you get any improvement, pls reward with points....

  • Performance: Processing Commands in loops

    textDropCap->Set(wordLength+1);
    paraAttributeBossList->ApplyAttribute(textDropCap);
    InterfacePtr<ICommand> applyAttrCmd(textModelCmds->ApplyCmd(start,
         1,
         paraAttributeBossList,
         kParaAttrStrandBoss));
    CmdUtils::ProcessCommand(applyAttrCmd);
    I am trying to set the drop cap word length for every paragraph in a IAttributeStrand and it is taking very long. Is there any way to get better performance out of processing commands?

    Maybe someone can help me figure this out. It turns out it is only very very slow on my Vista 64bit computer, but on my old laptop that is running Vista 32bit it is fast.

  • Performance syntax loop at  and read table

    in the routine , for reading one line in a internal table  , the syntaxe
      loop at  xxx where   and read tabl exxx   with key     XXXX
    has a great difference on performance or not?

    Loop at statement is used only for processing multiple records.Read table is used for reading a particluar record of an internal table.If you just need to check whether record exists in internal table, use can sort and use binary search with TRANSPORTING NO FIELDS addition. Also, try to use field symbols so that performance is increased.

  • Poor performance and loop

    Hello,
    I have a simple while loop in my JSP code which accesses a javabean data item on each iteration. The loop is causing a 2 � 3 second delay between converses of the web pages.
    Does any one else suffer the same type of performance sacrifices when using loops in their JSP code?
    Any suggestions of increasing the response time for the JSP?
    Code below,
    Thanks in advance.
    <% { int i = 0;
               String par;
               while (i < 99) {
                         par = (PARENT_SCREEN_ID.getTextValue(i));
                             if (par.equals("SM")) { %> mm_menu_1120099999_1_1.addMenuItem("<%= SCREEN_MSG.getTextValue(i) %>", "clickNav('<%= NAV_SCREEN_ID.getTextValue(i) %>');"); 
                                  <% } else if (par.equals("DM")) { %> mm_menu_1120099999_1_2.addMenuItem("<%= SCREEN_MSG.getTextValue(i) %>", "clickNav('<%= NAV_SCREEN_ID.getTextValue(i) %>');");
                                  <% } else if (par.equals("AM")) { %> mm_menu_1120099999_1_3.addMenuItem("<%= SCREEN_MSG.getTextValue(i) %>", "clickNav('<%= NAV_SCREEN_ID.getTextValue(i) %>');");
                                  <% } else if (par.equals("PM")) { %> mm_menu_1120099999_1_4.addMenuItem("<%= SCREEN_MSG.getTextValue(i) %>", "clickNav('<%= NAV_SCREEN_ID.getTextValue(i) %>');");
                                  <% } else if (par.equals("FM")) { %> mm_menu_1120099999_1_5.addMenuItem("<%= SCREEN_MSG.getTextValue(i) %>", "clickNav('<%= NAV_SCREEN_ID.getTextValue(i) %>');");
                                  <% } else if (par.equals("MC")) { %> mm_menu_1120099999_1_7.addMenuItem("<%= SCREEN_MSG.getTextValue(i) %>", "clickNav('<%= NAV_SCREEN_ID.getTextValue(i) %>');");
                                  <% } else if (par.equals("EM")) { %> mm_menu_1120099999_1_8.addMenuItem("<%= SCREEN_MSG.getTextValue(i) %>", "clickNav('<%= NAV_SCREEN_ID.getTextValue(i) %>');");
                                  <% } else if (par.equals(" ")) { i = 98;
                        } i = i + 1;
               } %>     

    Does any one else suffer the same type of performance sacrifices when using loops in their JSP code?only if i write badly performing loops.
    The fact its JSP is irrelavant, my guess is that your loop is very slow.
    Its hard to pinpoint where its slow becuase with all the sriplets its hard to read
    Some weird things to, you write PARENT_SCREEN_ID.getTextValue(i)
    This looks like you execute a method on a constant, its confusing too, what is that PARENT_SCREEN_ID ? what does the getTextValue do ?

  • Performance issue in Loop statement.

    Hi experts,
    I got an issue regarding performance in the loop statement. (IT_OUT_FINAL has huge amount of data.)
    LOOP AT it_out_final INTO wa_out_final.
    READ TABLE it_prdline_txt
    WITH KEY ydprodln = wa_out_final-prdline.
    IF sy-subrc = 0.
    wa_out_final-prdline = it_prdline_txt-ydvtext.
    MODIFY it_out_final FROM wa_out_final TRANSPORTING prdline.
    CLEAR: wa_out_final.
    ENDIF.
    read table i_sokna with key kunnr = wa_out_final-kunnr.
    if sy-subrc eq 0.
    wa_out_final-soreg = i_sokna-regio.
    MODIFY it_out_final FROM wa_out_final TRANSPORTING soreg.
    endif.
    read table i_sokna with key kunnr = wa_out_final-kunwe.
    if sy-subrc eq 0.
    wa_out_final-shreg = i_sokna-regio.
    MODIFY it_out_final FROM wa_out_final TRANSPORTING shreg.
    endif.
    clear : i_sokna,wa_out_final.
    ENDLOOP.
    Can you please help me , how to improve the performance in the above loop statement.
    Thanks,
    Revanth Kumar
    Moderator message: duplicate post locked.
    Edited by: Thomas Zloch on Jun 20, 2011 1:22 PM

    Hi,
    This one helped me in understanding the basics clearly. But I would like to further give you one example by which my question will be more clear to you and hence your further answer to it will help me in getting the idea about WHERE clause clarified.
    I was required to develop a report of all held docs by the SAP USER that were created through transaction FB60, the input obtained from user should be SAP USERNAME(obligatory).
    So the straight approach by me was that writing a SELECT-OPTIONS asking SAP USERNAME, and such username obtained from USER executing a report will be compared with the USERNAME stored in the column of table RFDT which stores all such held docs by a SAP USER that used transaction FB60 to temporarily hold it.
    So the approach used by me was using the select statement fetch all records from the column storing the SAP USERNAMES that have held docs using FB60 transaction and where clause is used to filter out only values matching the values obtained from user i.e. using SELECT-OPTIONS.
    So I was under the impression that WHERE clause can only be used in SELECT STATEMENT and not in LOOP AT...ENDLOOP.
    Now I hope my question is more clear to you. If I am not wrong, there can be two approaches,
    1) Using a SELECT statement containing the WHERE clause, fetch a resultset and then using LOOP...ENDLOOP. statement, display the output of the report using WRITE statement.
    i.e. SELECT...WHERE...ENDSELECT and then LOOP AT...ENDLOOP.
    2) Using SELECT statement, fetch all possible records and using LOOP...ENDLOOP. statement filter out the records using WHERE to match the resultset and display values in that resultset using WRITE statement
    i.e. SELECT...ENDSELECT and then LOOP AT...WHERE...ENDLOOP.
    Hope you will now be able to guide me better.
    Regards
    Ameet

  • Delete in loop

    Hi,
    I have a delete statement inside a loop like
    LOOP AT DATA_PACKAGE.
        lv_tabix = sy-tabix.
        clear gt_mattab.
        READ TABLE gt_mattab
        WITH KEY MATERIAL = DATA_PACKAGE-MATERIAL.
        IF SY-SUBRC NE 0.
          DELETE DATA_PACKAGE index lv_tabix.
        ENDIF.
      ENLOOP.
    Can you please help me in deleting the data packages with out using it in the loop?
    Will that increase the performance of the code and how?

    Hi Prasad,
    Let me explain exactly what happens if u delete a record from the internal table.
    If u defined your internal table like TYPE STANDARD TABLE OF or TYPE SORTED TABLE OF then it will work on INDEX mechanism.
    So if have 100 records in ur internal table then each record will be identified with its position i.e INDEX. When u delete a record from the table then it has to recreate the indexes for all other records(Except in case of deletion of last record) after that record. It is the majar disadvantage of delete statement. If u use delete statement inside loop this process has to happen equal to number of deletions.
    So there is one more solution for this which will be faster than
    DELETE inside the loop. Instead of deleting the records from the original table APPEND the records to another internal table.In this case it has to create INDEX for one time for one append in contrary to DELETE whcih has to recreate INDEXS for all rows.
    Check the logic below. Implement and use SQL trace to moniter the performance(transaction ST05).
    LOOP AT DATA_PACKAGE.
    lv_tabix = sy-tabix.
    clear gt_mattab.
    READ TABLE gt_mattab
    WITH KEY MATERIAL = DATA_PACKAGE-MATERIAL.
    CHECK SY-SUBRC EQ 0.
    APPEND DATA_PACKAGE TO DATA_PACKAGE1.
    ENLOOP.
    Also if u dont have else part and no code after ENDIF then always use CHECK statement which is much faster than IF.
    Thanks,
    Vinod.
    Edited by: Vinod Kumar Vemuru on Mar 20, 2008 6:32 PM

  • ABAP Performance standards good piece

    ABAP Performance Standards
    Following are the performance standards need to be following in writing ABAP programs:
    <b>1. Unused/Dead code</b>
    Avoid leaving unused code in the program. Either comment out or delete the unused situation. Use program --> check --> extended program to check for the variables, which are not used statically.
    <b>2. Subroutine Usage</b>
    For good modularization, the decision of whether or not to execute a subroutine should be made before the subroutine is called. For example:
    This is better:
    IF f1 NE 0.
    PERFORM sub1.
    ENDIF.
    FORM sub1.
    ENDFORM.
    Than this:
    PERFORM sub1.
    FORM sub1.
    IF f1 NE 0.
    ENDIF.
    ENDFORM.
    <b>3. Usage of IF statements</b>
    When coding IF tests, nest the testing conditions so that the outer conditions are those which are most likely to fail. For logical expressions with AND , place the mostly likely false first and for the OR, place the mostly likely true first.
    Example - nested IF's:
    IF (least likely to be true).
    IF (less likely to be true).
    IF (most likely to be true).
    ENDIF.
    ENDIF.
    ENDIF.
    Example - IF...ELSEIF...ENDIF :
    IF (most likely to be true).
    ELSEIF (less likely to be true).
    ELSEIF (least likely to be true).
    ENDIF.
    Example - AND:
    IF (least likely to be true) AND
    (most likely to be true).
    ENDIF.
    Example - OR:
    IF (most likely to be true) OR
    (least likely to be true).
    <b>4. CASE vs. nested Ifs</b>
    When testing fields "equal to" something, one can use either the nested IF or the CASE statement. The CASE is better for two reasons. It is easier to read and after about five nested IFs the performance of the CASE is more efficient.
    <b>5. MOVE statements</b>
    When records a and b have the exact same structure, it is more efficient to MOVE a TO b than to MOVE-CORRESPONDING a TO b.
    MOVE BSEG TO *BSEG.
    is better than
    MOVE-CORRESPONDING BSEG TO *BSEG.
    <b>6. SELECT and SELECT SINGLE</b>
    When using the SELECT statement, study the key and always provide as much of the left-most part of the key as possible. If the entire key can be qualified, code a SELECT SINGLE not just a SELECT. If you are only interested in the first row or there is only one row to be returned, using SELECT SINGLE can increase performance by up to three times.
    <b>7. Small internal tables vs. complete internal tables</b>
    In general it is better to minimize the number of fields declared in an internal table. While it may be convenient to declare an internal table using the LIKE command, in most cases, programs will not use all fields in the SAP standard table.
    For example:
    Instead of this:
    data: t_mara like mara occurs 0 with header line.
    Use this:
    data: begin of t_mara occurs 0,
    matnr like mara-matnr,
    end of t_mara.
    <b>8. Row-level processing and SELECT SINGLE</b>
    Similar to the processing of a SELECT-ENDSELECT loop, when calling multiple SELECT-SINGLE commands on a non-buffered table (check Data Dictionary -> Technical Info), you should do the following to improve performance:
    o Use the SELECT into <itab> to buffer the necessary rows in an internal table, then
    o sort the rows by the key fields, then
    o use a READ TABLE WITH KEY ... BINARY SEARCH in place of the SELECT SINGLE command. Note that this only make sense when the table you are buffering is not too large (this decision must be made on a case by case basis).
    <b>9. READing single records of internal tables</b>
    When reading a single record in an internal table, the READ TABLE WITH KEY is not a direct READ. This means that if the data is not sorted according to the key, the system must sequentially read the table. Therefore, you should:
    o SORT the table
    o use READ TABLE WITH KEY BINARY SEARCH for better performance.
    <b>10. SORTing internal tables</b>
    When SORTing internal tables, specify the fields to SORTed.
    SORT ITAB BY FLD1 FLD2.
    is more efficient than
    SORT ITAB.
    <b>11. Number of entries in an internal table</b>
    To find out how many entries are in an internal table use DESCRIBE.
    DESCRIBE TABLE ITAB LINES CNTLNS.
    is more efficient than
    LOOP AT ITAB.
    CNTLNS = CNTLNS + 1.
    ENDLOOP.
    <b>12. Performance diagnosis</b>
    To diagnose performance problems, it is recommended to use the SAP transaction SE30, ABAP/4 Runtime Analysis. The utility allows statistical analysis of transactions and programs.
    <b>13. Nested SELECTs versus table views</b>
    Since releASE 4.0, OPEN SQL allows both inner and outer table joins. A nested SELECT loop may be used to accomplish the same concept. However, the performance of nested SELECT loops is very poor in comparison to a join. Hence, to improve performance by a factor of 25x and reduce network load, you should either create a view in the data dictionary then use this view to select data, or code the select using a join.
    <b>14. If nested SELECTs must be used</b>
    As mentioned previously, performance can be dramatically improved by using views instead of nested SELECTs, however, if this is not possible, then the following example of using an internal table in a nested SELECT can also improve performance by a factor of 5x:
    Use this:
    form select_good.
    data: t_vbak like vbak occurs 0 with header line.
    data: t_vbap like vbap occurs 0 with header line.
    select * from vbak into table t_vbak up to 200 rows.
    select * from vbap
    for all entries in t_vbak
    where vbeln = t_vbak-vbeln.
    endselect.
    endform.
    Instead of this:
    form select_bad.
    select * from vbak up to 200 rows.
    select * from vbap where vbeln = vbak-vbeln.
    endselect.
    endselect.
    endform.
    Although using "SELECT...FOR ALL ENTRIES IN..." is generally very fast, you should be aware of the three pitfalls of using it:
    Firstly, SAP automatically removes any duplicates from the rest of the retrieved records. Therefore, if you wish to ensure that no qualifying records are discarded, the field list of the inner SELECT must be designed to ensure the retrieved records will contain no duplicates (normally, this would mean including in the list of retrieved fields all of those fields that comprise that table's primary key).
    Secondly, if you were able to code "SELECT ... FROM <database table> FOR ALL ENTRIES IN TABLE <itab>" and the internal table <itab> is empty, then all rows from <database table> will be retrieved.
    Thirdly, if the internal table supplying the selection criteria (i.e. internal table <itab> in the example "...FOR ALL ENTRIES IN TABLE <itab> ") contains a large number of entries, performance degradation may occur.
    <b>15. SELECT * versus SELECTing individual fields</b>
    In general, use a SELECT statement specifying a list of fields instead of a SELECT * to reduce network traffic and improve performance. For tables with only a few fields the improvements may be minor, but many SAP tables contain more than 50 fields when the program needs only a few. In the latter case, the performace gains can be substantial. For example:
    Use:
    select vbeln auart vbtyp from table vbak
    into (vbak-vbeln, vbak-auart, vbak-vbtyp)
    where ...
    Instead of using:
    select * from vbak where ...
    <b>16. Avoid unnecessary statements</b>
    There are a few cases where one command is better than two. For example:
    Use:
    append <tab_wa> to <tab>.
    Instead of:
    <tab> = <tab_wa>.
    append <tab> (modify <tab>).
    And also, use:
    if not <tab>[] is initial.
    Instead of:
    describe table <tab> lines <line_counter>.
    if <line_counter> > 0.
    <b>17. Copying or appending internal tables</b>
    Use this:
    <tab2>[] = <tab1>[]. (if <tab2> is empty)
    Instead of this:
    loop at <tab1>.
    append <tab1> to <tab2>.
    endloop.
    However, if <tab2> is not empty and should not be overwritten, then use:
    append lines of <tab1> [from index1] [to index2] to <tab2>.
    Hope this will help you all in writing the ABAP program.<b></b>

    ABAP Performance Standards
    Following are the performance standards need to be following in writing ABAP programs:
    <b>1. Unused/Dead code</b>
    Avoid leaving unused code in the program. Either comment out or delete the unused situation. Use program --> check --> extended program to check for the variables, which are not used statically.
    <b>2. Subroutine Usage</b>
    For good modularization, the decision of whether or not to execute a subroutine should be made before the subroutine is called. For example:
    This is better:
    IF f1 NE 0.
    PERFORM sub1.
    ENDIF.
    FORM sub1.
    ENDFORM.
    Than this:
    PERFORM sub1.
    FORM sub1.
    IF f1 NE 0.
    ENDIF.
    ENDFORM.
    <b>3. Usage of IF statements</b>
    When coding IF tests, nest the testing conditions so that the outer conditions are those which are most likely to fail. For logical expressions with AND , place the mostly likely false first and for the OR, place the mostly likely true first.
    Example - nested IF's:
    IF (least likely to be true).
    IF (less likely to be true).
    IF (most likely to be true).
    ENDIF.
    ENDIF.
    ENDIF.
    Example - IF...ELSEIF...ENDIF :
    IF (most likely to be true).
    ELSEIF (less likely to be true).
    ELSEIF (least likely to be true).
    ENDIF.
    Example - AND:
    IF (least likely to be true) AND
    (most likely to be true).
    ENDIF.
    Example - OR:
    IF (most likely to be true) OR
    (least likely to be true).
    <b>4. CASE vs. nested Ifs</b>
    When testing fields "equal to" something, one can use either the nested IF or the CASE statement. The CASE is better for two reasons. It is easier to read and after about five nested IFs the performance of the CASE is more efficient.
    <b>5. MOVE statements</b>
    When records a and b have the exact same structure, it is more efficient to MOVE a TO b than to MOVE-CORRESPONDING a TO b.
    MOVE BSEG TO *BSEG.
    is better than
    MOVE-CORRESPONDING BSEG TO *BSEG.
    <b>6. SELECT and SELECT SINGLE</b>
    When using the SELECT statement, study the key and always provide as much of the left-most part of the key as possible. If the entire key can be qualified, code a SELECT SINGLE not just a SELECT. If you are only interested in the first row or there is only one row to be returned, using SELECT SINGLE can increase performance by up to three times.
    <b>7. Small internal tables vs. complete internal tables</b>
    In general it is better to minimize the number of fields declared in an internal table. While it may be convenient to declare an internal table using the LIKE command, in most cases, programs will not use all fields in the SAP standard table.
    For example:
    Instead of this:
    data: t_mara like mara occurs 0 with header line.
    Use this:
    data: begin of t_mara occurs 0,
    matnr like mara-matnr,
    end of t_mara.
    <b>8. Row-level processing and SELECT SINGLE</b>
    Similar to the processing of a SELECT-ENDSELECT loop, when calling multiple SELECT-SINGLE commands on a non-buffered table (check Data Dictionary -> Technical Info), you should do the following to improve performance:
    o Use the SELECT into <itab> to buffer the necessary rows in an internal table, then
    o sort the rows by the key fields, then
    o use a READ TABLE WITH KEY ... BINARY SEARCH in place of the SELECT SINGLE command. Note that this only make sense when the table you are buffering is not too large (this decision must be made on a case by case basis).
    <b>9. READing single records of internal tables</b>
    When reading a single record in an internal table, the READ TABLE WITH KEY is not a direct READ. This means that if the data is not sorted according to the key, the system must sequentially read the table. Therefore, you should:
    o SORT the table
    o use READ TABLE WITH KEY BINARY SEARCH for better performance.
    <b>10. SORTing internal tables</b>
    When SORTing internal tables, specify the fields to SORTed.
    SORT ITAB BY FLD1 FLD2.
    is more efficient than
    SORT ITAB.
    <b>11. Number of entries in an internal table</b>
    To find out how many entries are in an internal table use DESCRIBE.
    DESCRIBE TABLE ITAB LINES CNTLNS.
    is more efficient than
    LOOP AT ITAB.
    CNTLNS = CNTLNS + 1.
    ENDLOOP.
    <b>12. Performance diagnosis</b>
    To diagnose performance problems, it is recommended to use the SAP transaction SE30, ABAP/4 Runtime Analysis. The utility allows statistical analysis of transactions and programs.
    <b>13. Nested SELECTs versus table views</b>
    Since releASE 4.0, OPEN SQL allows both inner and outer table joins. A nested SELECT loop may be used to accomplish the same concept. However, the performance of nested SELECT loops is very poor in comparison to a join. Hence, to improve performance by a factor of 25x and reduce network load, you should either create a view in the data dictionary then use this view to select data, or code the select using a join.
    <b>14. If nested SELECTs must be used</b>
    As mentioned previously, performance can be dramatically improved by using views instead of nested SELECTs, however, if this is not possible, then the following example of using an internal table in a nested SELECT can also improve performance by a factor of 5x:
    Use this:
    form select_good.
    data: t_vbak like vbak occurs 0 with header line.
    data: t_vbap like vbap occurs 0 with header line.
    select * from vbak into table t_vbak up to 200 rows.
    select * from vbap
    for all entries in t_vbak
    where vbeln = t_vbak-vbeln.
    endselect.
    endform.
    Instead of this:
    form select_bad.
    select * from vbak up to 200 rows.
    select * from vbap where vbeln = vbak-vbeln.
    endselect.
    endselect.
    endform.
    Although using "SELECT...FOR ALL ENTRIES IN..." is generally very fast, you should be aware of the three pitfalls of using it:
    Firstly, SAP automatically removes any duplicates from the rest of the retrieved records. Therefore, if you wish to ensure that no qualifying records are discarded, the field list of the inner SELECT must be designed to ensure the retrieved records will contain no duplicates (normally, this would mean including in the list of retrieved fields all of those fields that comprise that table's primary key).
    Secondly, if you were able to code "SELECT ... FROM <database table> FOR ALL ENTRIES IN TABLE <itab>" and the internal table <itab> is empty, then all rows from <database table> will be retrieved.
    Thirdly, if the internal table supplying the selection criteria (i.e. internal table <itab> in the example "...FOR ALL ENTRIES IN TABLE <itab> ") contains a large number of entries, performance degradation may occur.
    <b>15. SELECT * versus SELECTing individual fields</b>
    In general, use a SELECT statement specifying a list of fields instead of a SELECT * to reduce network traffic and improve performance. For tables with only a few fields the improvements may be minor, but many SAP tables contain more than 50 fields when the program needs only a few. In the latter case, the performace gains can be substantial. For example:
    Use:
    select vbeln auart vbtyp from table vbak
    into (vbak-vbeln, vbak-auart, vbak-vbtyp)
    where ...
    Instead of using:
    select * from vbak where ...
    <b>16. Avoid unnecessary statements</b>
    There are a few cases where one command is better than two. For example:
    Use:
    append <tab_wa> to <tab>.
    Instead of:
    <tab> = <tab_wa>.
    append <tab> (modify <tab>).
    And also, use:
    if not <tab>[] is initial.
    Instead of:
    describe table <tab> lines <line_counter>.
    if <line_counter> > 0.
    <b>17. Copying or appending internal tables</b>
    Use this:
    <tab2>[] = <tab1>[]. (if <tab2> is empty)
    Instead of this:
    loop at <tab1>.
    append <tab1> to <tab2>.
    endloop.
    However, if <tab2> is not empty and should not be overwritten, then use:
    append lines of <tab1> [from index1] [to index2] to <tab2>.
    Hope this will help you all in writing the ABAP program.<b></b>

  • Adding parallel loops programatically

    Hi!
    I'm building a system with some instruments and I want to use the same instrument-VI for all instruments.
    One way is to do it set it up as 'Possible solution..' (see image).
    Is there some way where I can loop through the 'hardware settings'-array and create as many as necessary? Like the 'More what I want...' (see image)?
    Attachments:
    parallel loops.PNG ‏15 KB

    Hello again thread!
    So I'm back on the same problem...
    Summary:
    What I want to do is something like in the new picture 'parallel loops2.png'. Start X parallel loops that each handle the communication with a specific instrument. At the moment I have 9 instruments connected.
    If I use 'Configure Iteration Parallelism' I can set the 'Number of generated parallel loop instances' to the max number (=64 for me) and then use the P terminal with the 'array size' VI to get my 9 instrumentloops running.
    When reading this white paper
    http://www.ni.com/white-paper/9393/en/ ('Improving Performance with Parallel For Loops')
    I'm getting the feeling that the way I solved it is not the way right way. Since the P-terminal should equal the number of cores in the computer.
    The Run! VI does not have any outputs wired to its connector pane. It is reentrant (Preallocate clones - No debugging allowed).
    I havn't looked at Asyncchronous calls yet. Is that the way to go?
    Attachments:
    parallel loops2.PNG ‏3 KB

  • Coming out of loop

    DEAR TECHIS,,
    plz tell me the way to come out from the loop of item table
    i have devloped a bdc prog for Customer invoice fb70. for that i have used  two tables for header and item. here my problem is after posting the data. the loop is not breaking of item table to undersanding pupuse i m giving smalle
    as
    loop at header .
    performe...
            loop at item where acnt = header-acnt.
    perform........
           endloop.
    endloop.
    Here i didnt get the way to come out from the item tables loop.
    pls reply....
    Rewards for useful ans..
    thanks in advance...

    Hi Devalla,
    It's of sure that, your are looping the item table only when you have the acnt = header-acnt, in the Where condition of the loop.
    Stilll you find that your loop is not breaking up means its really a ?
    Try to debug and find out where is the probs?
    okay .. if you want to come out conditionally, place EXIT command at the begining or at the end of the Loop by placing a CHECK. with whatever you want either using the count of number of entries in the item table with respect to the header acnt field.
    if thing it's sure it's going to be some simple thing which block you...
    If still cant post the code.. with where it hooks...
    Reward points if useful

  • To exit from the while(1) loop

    Hi all ,
    I have a simple question that if in a callback function of a command button, i use a While(bLoop)
    loop , where bLoop is a boolean variable initially set to TRUE, then how can i break or exit from this while Loop by using a control on the front panel  , which exits the while loop by setting     bLoop = FALSE .
    I have tried it but it is not exiting  
    Solved!
    Go to Solution.

    The problem here is that CVI normally only executes one callback at a time. While you are in one control callback, no GUI processing and subsequent calls to other callbacks normally occurs.
    You can try the following approach - but it is not really the best method:
        while (b_loop) {              // Inside a callback
            ...                       // Perform your tight program loop
            ProcessSystemEvents ();   // Force CVI to see if any GUI controls need servicing
    If you have a different control callback to clear the global b_loop, this quick-and-dirty approach might work for you.
    You should only use this technique for very simple programs - it can rapidly spiral out of control and end up in a mess if you're not careful. NI recommends that you do not use ProcessSystemEvents() inside a control callback.
    JR

  • NESTED LOOP or SORT MERGE

    Hi All,
    How can we judge which one is best to use for the query- NESTED LOOP
    - SORT MERGE
    - HASH JOINThanx.. Ratan

    Hi...
    For Nested Loop Joins:
    Nested loop joins are useful when small subsets of data are being joined and if the join condition is an efficient way of accessing the second table.
    It is very important to ensure that the inner table is driven from (dependent on) the outer table. If the inner table's access path is independent of the outer table, then the same rows are retrieved for every iteration of the outer loop, degrading performance considerably. In such cases, hash joins joining the two independent row sources perform better.
    For Hash Join:
    Hash joins are used for joining large data sets. The optimizer uses the smaller of two tables or data sources to build a hash table on the join key in memory. It then scans the larger table, probing the hash table to find the joined rows.
    For Sort Merge Joins:
    Sort merge joins can be used to join rows from two independent sources. Hash joins generally perform better than sort merge joins. On the other hand, sort merge joins can perform better than hash joins if both of the following conditions exist:
    The row sources are sorted already.
    A sort operation does not have to be done.
    However, if a sort merge join involves choosing a slower access method (an index scan as opposed to a full table scan), then the benefit of using a sort merge might be lost.
    Sort merge joins are useful when the join condition between two tables is an inequality condition (but not a nonequality) like <, <=, >, or >=. Sort merge joins perform better than nested loop joins for large data sets. You cannot use hash joins unless there is an equality condition.
    In a merge join, there is no concept of a driving table. The join consists of two steps:
    Sort join operation: Both the inputs are sorted on the join key.
    Merge join operation: The sorted lists are merged together.
    If the input is already sorted by the join column, then a sort join operation is not performed for that row source.

  • Performance Measure - Select SUM and Collect Statement.

    Dear All,
    I am using YNME_PROCESS_PO_CUST Badi in this i writing some validation Delivery Completion.
    For that i need to calculate GR qty and Delivery quantity based on this i need some validation. But here i confussed which statement i need to use for bast performance.
    Note: In Badi Item Level Data will be process one by one..like item level 10 then 20 then 30......Like that
    Code will like that---
    SELECT  SUM( menge )  FROM ekes
                                INTO  l_delqty
                                WHERE ebeln =  ls_mepoitem-ebeln
                                AND   ebelp =    ls_mepoitem-ebelp.
            SELECT  SUM( dabmg  )  FROM ekes
                             INTO  l_grqty
                             WHERE ebeln =  ls_mepoitem-ebeln
                             AND   ebelp =  ls_mepoitem-ebelp.
            l_delqty1 =  l_grqty - l_delqty.
            IF l_delqty1 NE 0.
              ls_mepoitem-elikz = ''.
              CALL METHOD im_item->set_data( ls_mepoitem ).
            ENDIF.
    I check in SE38 response is better in this code.
    Other code may be like that .. same data will be like upper/
          SELECT * FROM ekes
                     INTO CORRESPONDING FIELDS OF TABLE it_ekes
                     WHERE ebeln =  ls_mepoitem-ebeln
                     AND    ebelp =   ls_mepoitem-ebelp.
          LOOP AT it_ekes.
            MOVE-CORRESPONDING it_ekes TO it_ekes1.
            COLLECT it_ekes1.
            CLEAR  it_ekes.
          ENDLOOP.
          READ TABLE it_ekes1 INDEX 1.
          IF sy-subrc EQ 0.
            l_delqty1 =  it_ekes1-menge - it_ekes1-dabmg.
          ENDIF.
        IF l_delqty1 NE 0.
              ls_mepoitem-elikz = ''.
              CALL METHOD im_item->set_data( ls_mepoitem ).
       ENDIF.
    Can any send me document--
    Regard
    DK

    Hi,
    Single Select statement is certainly better.
    But no need to do select * and using into corresponding fields. These will reduce the performance. Also the loop statment is not absolutely correct. Following could be a sample code.
    TYPES: BEGIN OF gx_ekes,  (maintaining same sequence of fields as in select statement, this way no need of into corresponding fields)
                 ebeln type ebeln,
                 ebelp type ebelp,
                 menge type bbmng,
                 dabmg type dabmg,
                 END OF gx_ekes.
    DATA : lit_ekes TYPE TABLE OF gx_ekes,
                git_ekes TYPE TABLE OF gx_ekes,
                wa_ekes TYPE gx_ekes.
    SELECT ebeln
                  ebelp
                  menge
                  dabmg
    FROM ekes
      INTO TABLE it_ekes
    WHERE ebeln = ls_mepoitem-ebeln
    AND ebelp = ls_mepoitem-ebelp.
    LOOP AT lit_ekes INTO wa_ekes.
    COLECT wa_ekes INTO git_ekes.
    CLEAR: wa_ekes.
    ENDLOOP.
    CLEAR: lit_ekes.
    Now the first record in git_ekes will have the sum as only one line item is being passed in the user exit.
    Regards,
    Pranav.

Maybe you are looking for

  • Delete files from startup disk?

    Under system preferences I see the StartUp Disk, but where do I delete files from that in order to clear up some space? I have MacBook Air OS 10.6.8. Is it just under my User? everything like applications and documents, etc?

  • Sorting by second in Adobe Bridge

    For those of you familiar with sorting from multiple cameras in Bridge: When sorting our wedding photos, I can't seem to get Bridge to sort the  Date Created down to the second. It is sorting to the minute, and with  two cameras firing at the same ti

  • Regarding connection reset exception in socket

    hi, I am using java socket on one side and c socket on other side iam trying to send data and recieve from it but i got error socketexception connection reset by the peer, Environment which i am using to open a socket is websphere studio test environ

  • Create Table taking long time (more than 60 minutes) and still running

    Hi all, I was able to create and drop table until yesterday, but now the when I issue the below statement the server is stuck, its showing creating table in process.... and then it hangs till you cancel the operation. Query of table and running the p

  • Problem in installation exit code: 1603

    I'm trying to install my lightroom 5 true the Creative Cloud, when the instalation appear to 42% then stopped and the error informed in summary it's: Exit Code: 7 Please see specific errors below for troubleshooting. For example,  ERROR: ------------