Which is better? Code comparsion of performance and style

Recently I run into a discussion over a small piece of code. Could help me which is better, either in performance or coding style? The code is not complete, the question is the use of local cancellationNumber variable.
public String cancelAction(/**/) {
/* some code */
        String cancellationNumber = result.getCancellationNumber();
        if (empty(cancellationNumber)) {
            throw new Exception("Did not receive a cancellation number!");
        return cancellationNumber;
    }or
public String cancelAction(/**/) {
/* some code */
        if (empty(result.getCancellationNumber()) {
            throw new Exception("Did not receive a cancellation number!");
        return result.getCancellationNumber();
    }

Yes, I know profiling can be misleading, also compiler optimization adds to the picture. However seeing the numbers differentially, I think there is still some information, which is faster, even if taking it completely out scope. I didn't paste the code, because it's so trivial. I run the two methods in a loop with same arguments.
With increased loop count, the difference is 6-7%, cancelActionWithLocal being faster. But this can be pointless, I know.
package org.helloprofile;
import static org.helloprofile.Util.empty;
import java.util.Locale;
public class CUT {
    public String cancelActionWithoutLocal(Locale locale, String email, long itineraryId, String confirmationId) throws Exception {
        Result result = new Result();
        if (empty(result.getCancellationNumber())) {
            throw new Exception("Did not receive a cancellation number!");
        return result.getCancellationNumber();
    public String cancelActionWithLocal(Locale locale, String email, long actionId, String confirmationId) throws Exception {
        Result result = new Result();
        String cancellationNumber = result.getCancellationNumber();
        if (empty(cancellationNumber)) {
            throw new Exception("Did not receive a cancellation number!");
        return cancellationNumber;
}Thanks for the comments!

Similar Messages

  • Code comparission which is better in terms of performance

    In my pl/sql procedure the following code exist
    SELECT count(*) INTO L_exists
              FROM txt
         WHERE templ_id in (ISecurTempl,ESecurTempl);
    Now i want to replace the query with
    SELECT count(*) INTO L_exists
              FROM txt
    WHERE templ_id in (                                                       SELECT INT_SEC_TMP FROM table(cast(parse_table as sec_template_tbl))
                                                      UNION
    SELECT EXT_SEC_TMP FROM table(cast(parse_table as sec_template_tbl))
    Can you please tell me which part of code is better in terms of performance
    and why?
    Thanks in advance

    I want to know which is betterThere's not enough information for anyone here to be able to tell you.
    Obviously the first one "looks" faster, but without knowing the tables, structure, data, indexes, platform etc. etc. etc. we won't have a clue.

  • Which is better in terms of performance

    Dear All,
    which is better..
    to use FOR ALL ENTRIES      or
    to build a range and use  WHERE IN RANGE_TABLE     .. Does this have data limitation problem.
    is there a better method?
    Thanks,
    Raghavendra
    Moderator message - Please search before asking - post locked
    Edited by: Rob Burbank on Jul 7, 2009 10:53 AM

    I want to know which is betterThere's not enough information for anyone here to be able to tell you.
    Obviously the first one "looks" faster, but without knowing the tables, structure, data, indexes, platform etc. etc. etc. we won't have a clue.

  • Applicant Conversion - Which is better of the 2 options and why?

    Hi -
    I needed your technical expertise to identify the easiest and most efficient method I should take for converting the applicants -
    First option is to Convert the candidate into an applicant by applying to an existing vacancy (This is similar approach we do in the front end ).
    Potential API Internal Name: CONVERT_TO_APPLICANT
    Interface:HR_APPLICANT_API.
    Second method is a two step process, convert the candidate into an applicant, then creating applicant assignment for all the jobs the candidate has applied for.
    Potential API Internal Name: ACTIVATE_EMP_ASG, CREATE_SECONDARY_APL_ASG
    Interface:HR_ASSIGNMENT_API
    Which approach do you experts think would be the best option and why?
    Early response is much appreciated.
    Many Thanks,
    Dinesh Babuji

    If you are looking applicant creation without Assignment , Ist option is good
    If you are looking applicant creation with Assignment , IInd option is good
    Thanks

  • Which is better for gaming and why?

    Hi,
    I was researching budget gaming laptops(around $1000, INR 55000) and came up with two choices.....
    1)HP Pavilion g6z-1d00 Notebook PC
    http://shopping2.hp.com/en_US/home-office/-/products/Laptops/HP-Pavilion/A2B39AV?HP-Pavilion-g6z-1d0...
    2)HP Envy 14-2130nr Notebook PC
    http://shopping2.hp.com/en_US/home-office/-/products/Laptops/HP-ENVY/QE295UA?HP-ENVY-14-2130nr-Noteb...
    Could anybody please tell me which is better for gaming (main purpose and best performance)?
    The HP Envy looks great but I don't know much about AMD Quad Core.....
    Also, is it possible to upgrade the graphics card on the HP Envy ( AMD Radeon 6630 to a better one) via a HP centre?
    It seems to run most games quite well, but I need it to be able to play new games for at least 4 years more (college), while not factoring in the costs for any possible graphics card upgrade....
    Please help!!

    Thanks Huffer _ very useful.
     I wasn't aware that there was a heat problem with the i7 processors, my dv8 runs at around 42 to 52 degrees, mind you I don't really put it under much load. I use it to play Blu-ray ISO files on my projector and for photo editing (Adobe CS4), it's an 820QM.
     I have also changed the thermal compound to ICDiamond and drilled holes in the speaker cover to improve air flow, that made a difference too.
     @ abhishekmaha
     Don't take my comment to seriously, although I think it has some truth to it, it was meant to poke a bit of fun at you. 
     Heat has always been one of the biggest factors when it comes to any computer, designers try to make them thinner, lighter and cheaper and those types don't work for gaming very well. They're OK for the occasional one, but not on a regular basis. I believe that if you game on any machine that was not meant for it, you will not get 4 years out of it _ 2 years.
     I wish I could tell you different, but I am not going to lie to you.
     Heat basically affects 3 things on a laptop, the solder that holds the components on the motherboard, any mechanical moving parts, eg the hard drive, fan _ and the battery. You can remove the battery to prolong its life when gaming.
     Heat breaks down the solder over time and the mother board simply stops working as far as the hard drive, it stops spinning because the tiny bearing(s) in there dry out and seize up.
     If you don't want to use a cooling mat then prop up the back of the laptop, hanging it over the edge of the table will expose the fan intake, but will block off other vents.
     60 degrees is a bit warm too, 50 is better or rather, the cooler the better. What ever machine you get, make a note of what the temps are when you first boot up and when it's hot. The idea is to get an average so you can judge when it is dangerously getting hot.
     P.S. Be sure and give Huffer a kudos too.

  • Which is better, a G4-450 Dual or a Mac Mini 1.42?

    which is better in terms of Sequencing and plug in performace, the G4-450 Dual or a Mac Mini 1.42?

    G4-450GHz Dual with 896MB RAM
    Mac Mini 1.42GHz with 1 gig of Ram
    G4-450GHz Dual gets more instances with plugs, more tracks and performance then the 1.4GHz 17" Powerbook, 12" powerbook and Mac Mini which all have the same G4 processor.,
    Today, i took the same 34 track session,
    -all 34 tracks have a Logic Comp, Eq, Gate
    -and also 8 Buses with Comp, EQ, Gates, Delays, Flange, Phasors, Pitch Shifters, 2 Reverbs (1 long and 1 plated) as well as some other toys.
    -Master with Waves Ren Comp, Logic EQ.
    -6 esx24 Instruments with high loads ( Harps, Strings, Cellos, Drums and Perc)
    -8 Long (16 Bar) drum tracks ( Bass, HH, Snare, Toms, Overheads, Fills, Percussion dubs)
    -4 Vocal takes and Dubs (more then 16 Bars long)
    -Bass Track
    -2 Acoustic stereo tracks
    -4 Guitar tracks, dubbs and fills
    -4 Slide Acoustic guitar tracks
    -4 dubbed effect vocal tracks
    AT first, he G4-450GHz Dual choked with 2 errors, then it buffered into the session well and played everything back fine of the same FW drive.
    The mac mini got major problems and only performed 28 tracks with the esx24 tracks frozen, and from time to time after heating up chokes again, i had to wait a few minutes before i bounced the session due to overload errors.
    Over all, Both have G4 Processors and about 1GIG ram (450GHz Dual is under 1 GIG), but its a clear fact that double processors win, even the lowest 450GHz Dual is still hotter then any flashy fast Bused mac mini, powerbook or iMac.

  • Which is better,websphere or weblogic?

    Our company want to establish a network serving for PC ,wap ,pda and so on using j2ee.but I don��t know which is better Between Websphere application server and Weblogic.
    Who can tell me in detail?

    Something to start with:
    WebSphere
    1. WebSphere covers more platforms.
    2. WebSphere has a better supportline (IBM know this stuff)
    3. Having DB2 as a database, you might want to use WebSphere, since it has a lots of advantages of using both the database and AppServer from the same Vendor.
    WebLogic:
    1. WebLogic is a more possisioned appserver
    2. I 'believe' weblogic is more up to date with java versions and technologies
    regards
    Andreas

  • I need a clarification : Can I use EJBs instead of helper classes for better performance and less network traffic?

    My application was designed based on MVC Architecture. But I made some changes to HMV base on my requirements. Servlet invoke helper classes, helper class uses EJBs to communicate with the database. Jsps also uses EJBs to backtrack the results.
    I have two EJBs(Stateless), one Servlet, nearly 70 helperclasses, and nearly 800 jsps. Servlet acts as Controler and all database transactions done through EJBs only. Helper classes are having business logic. Based on the request relevant helper classed is invoked by the Servlet, and all database transactions are done through EJBs. Session scope is 'Page' only.
    Now I am planning to use EJBs(for business logic) instead on Helper Classes. But before going to do that I need some clarification regarding Network traffic and for better usage of Container resources.
    Please suggest me which method (is Helper classes or Using EJBs) is perferable
    1) to get better performance and.
    2) for less network traffic
    3) for better container resource utilization
    I thought if I use EJBs, then the network traffic will increase. Because every time it make a remote call to EJBs.
    Please give detailed explanation.
    thank you,
    sudheer

    <i>Please suggest me which method (is Helper classes or Using EJBs) is perferable :
    1) to get better performance</i>
    EJB's have quite a lot of overhead associated with them to support transactions and remoteability. A non-EJB helper class will almost always outperform an EJB. Often considerably. If you plan on making your 70 helper classes EJB's you should expect to see a dramatic decrease in maximum throughput.
    <i>2) for less network traffic</i>
    There should be no difference. Both architectures will probably make the exact same JDBC calls from the RDBMS's perspective. And since the EJB's and JSP's are co-located there won't be any other additional overhead there either. (You are co-locating your JSP's and EJB's, aren't you?)
    <i>3) for better container resource utilization</i>
    Again, the EJB version will consume a lot more container resources.

  • Which is better for performance Azure SQL Database or SQL Server in Azure VM?

    Hi,
    We are building an ASP.NET app that will be running on Microsoft Cloud which I think is the new name for Windows Azure. We're expecting this app to have many simultaneous users and want to make sure that we provide excellent performance to end users.
    Here are our main concerns/desires:
    Performance is paramount. Fast response times are very very important
    We want to have as little to do with platform maintenance as possible e.g. managing OS or SQL Server updates, etc.
    We are trying to use "out-of-the-box" standard features.
    With that said, which option would give us the best possible database performance: a SQL Server instance running in a VM on Azure or SQL Server Database as a fully managed service?
    Thanks, Sam

    hello,
    SQL Database using shared resources on the Microsft data centre. Microsoft balance the resource usage of SQL Database so that no one application continuously dominates any resource.You can try the 
    Premium Preview
    for Windows Azure SQL Database which offers better performance by guaranteeing a fixed amount of dedicated resources for a database.
    If you using SQL Server instance running in a VM, you control the operating system and database configuration. And the
    performance of the database depends on many factors such as the size of a virtual machine, and the configuration of the data disks.
    Reference:
    Choosing between SQL Server in Windows Azure VM & Windows Azure SQL Database
    Regards,
    Fanny Liu
    If you have any feedback on our support, please click here. 
    Fanny Liu
    TechNet Community Support

  • Which is better of MANY_TO_ONE and ONE_TO_MANY

    I am trying je.
    A little confuse is , that suppose A has one_to_many relation to B, then B can have many_to_one relation to A. And both solution is acceptable to my application. Which should I choose?

    Hello Jie,
    This is a very good question, since we do not describe in the documentation how to choose between MANY_TO_ONE and ONE_TO_MANY. As you point out, it can be done either way when a related entity is used.
    For example, here is how MANY_TO_ONE can be used:
    @Entity
    class Person {
      @PrimaryKey(sequence="ID")
      long id;
      @SecondaryKey(relate=MANY_TO_ONE, relatedEntity=Employer.class)
      long employerId;
      String name;
    @Entity
    class Employer {
      @PrimaryKey(sequence="ID")
      long id;
      String description;
    }Of course we will need primary indexes for both entities:
    PrimaryIndex<Long,Person> personById = ...;
    PrimaryIndex<Long,Employer> employerById = ...;To get the employer of a person, we simply pass the employerId to the primary index:
    Person person = ...;
    Employer employer = employerById.get(person.employerId);To get the employees for a given employer, we get a sub-index for the employerId secondary key:
    long anEmployerId = ...;
    SecondaryIndex<Long,Long,Person> personByEmployerId = ...;
    EntityIndex<Long,Person> employees = personByEmployerId.subIndex(anEmployerId);
    EntityCursor<Person> cursor = employees.entities();
    try {
      for (Person employee : cursor) {
        // do something with employee
    } finally {
      cursor.close();
    }And here is how ONE_TO_MANY can be used to provide the same functionality:
    @Entity
    class Person {
      @PrimaryKey(sequence="ID")
      long id;
      String name;
    @Entity
    class Employer {
      @PrimaryKey(sequence="ID")
      long id;
      @SecondaryKey(relate=ONE_TO_MANY, relatedEntity=Person.class)
      Set<Long> employeeIds;
      String description;
    }To get the employer of a person, we simply pass the person id to the employer's secondary index:
    Person person = ...;
    SecondaryIndex<Long,Long,Employer> employerByEmployeeIds = ...;
    Employer employer = employerByEmployeeIds.get(person.id);The primary difference is that with MANY_TO_ONE the collection of employee IDs is maintained by the secondary index, while with ONE_TO_MANY the collection of employee IDs is embedded in the Employer entity.
    Therefore to get the employees for a given employer with ONE_TO_MANY, we get the Employer object from the employerById primary index and then get each person in the employeeIds set:
    long anEmployerId = ...;
    SecondaryIndex<Long,Long,Person> personByEmployerId = ...;
    Employer employer = employerById.get(anEmployerId);
    for (long employeeId : employer.employeeIds) {
      Person employee = personById.get(employeeId);
      // do something with employee
    }There is a major difference in terms of performance and scalability. With ONE_TO_MANY, if the number of employees for a single employer is very large, then the Employer record will be large because the list of employee IDs is embedded in the Employer object. This means that it will be more expensive to load the employer, for example, if all you want is the employer description field. The list of employee IDs will always be loaded whenever you access an employer.
    On the other hand, with MANY_TO_ONE, the set of employers is stored in the sub-index. The sub-index is a Btree. It is very scalable and can easily support large numbers of employees per employer, even millions. And when simply loading the Employer record, the set of employeeIds for that employer will not be loaded. The Employer record will be very small.
    There are four factors in deciding whether to use MANY_TO_ONE or ONE_TO_MANY.
    (1) As shown above, it is slightly easier to use ONE_TO_MANY, because you don't need to use a sub-index as you must do with MANY_TO_ONE.
    (2) MANY_TO_ONE will scale to larger number of entities per relationship, since a sub-index Btree is used to store the related entities.
    (3) With MANY_TO_ONE, the entity object will not grow to a large size as many related entities are added. Smaller records are always better for performance and resource consumption.
    In general, I advise using MANY_TO_ONE because it does not have the potential performance problems of ONE_TO_MANY (items 2 and 3 above).
    But if you know that the number of related entities per relationship will be small, then either technique works well, and you should choose whichever you prefer. You may find that ONE_TO_MANY is slightly easier to use (item 1 above). Or you may choose one technique over the other because you prefer to maintain the relationship via the Person.employerId field or the Employer.employeeIds set.
    There is one additional factor. If you have a secondary key where there is no related entity, just related keys, then you have no choice. There is only one entity, and you choose the relationship type accordingly.
    For example, a Person may have many email addresses, and you may choose not to have an EmailAddress entity. The email addresses are simply secondary keys, not the key of another related entity. If a user can only have one email address, you would use ONE_TO_ONE. If the user can have multiple email addresses, you would use ONE_TO_MANY as shown below.
    @Entity
    class Person {
      @PrimaryKey(sequence="ID")
      long id;
      @SecondaryKey(relate=ONE_TO_MANY)
      Set<String> emailAddresses;
      String name;
    }A gender (male or female) secondary key is an example of a MANY_TO_ONE relationship where no related entity is involved:
    @Entity
    class Person {
      @PrimaryKey(sequence="ID")
      long id;
      @SecondaryKey(relate=MANY_TO_ONE)
      char gender; // M or F
      String name;
    }In this last example, there is no choice about whether to use ONE_TO_MANY or MANY_TO_ONE because there is only one entity involved. So this last rule is:
    (4) If there is no related entity, then because there is only one entity involved the relationship type is determined by the cardinality (number) of entities and keys in each relationship.
    Mark

  • Which is better and why a = new String("AA") or a = "AA"

    Hi,
    Which is better and why
    String a = new String("AA") or
    String a = "AA"
    Does invoking a construtor waste memory? Please explain in detail.
    Thanks in advance
    Deepak

    > So in case "AA" not there in string pool,
    That is not correct.
    does new creates "AA" on string pool as well as heap memory?Yes. The literal "AA" points to a pooled String object. The new operator creates a new String object with the same character sequence ("AA"). You can verify this with a little code...
    String s = new String("AA");
    assert s != "AA";
    assert s.equals("AA");
    assert s.intern() == "AA";~

  • In and EXISTS??which is better and why

    hi...
    Performance wise which is better IN or EXISTS and why..

    user8469486 wrote:
    hi...
    Performance wise which is better IN or EXISTS and why..DomBrooks pointed out that it may not matter due to query optimization rewrites.
    In theory it depends on circumstances.
    Correlated EXISTS subqueries tend to be efficient if the lookup is properly indexed. If the list of values is very small (especially if you only get one value) an IN subquery might be more efficient.

  • Which is better:  extractValue or existsNode for Performance

    Hi,
    We have XMLDB Table with only 1 Column (XMLType) created using below:
    create table TNMAB_AGREEMENT_XML( AGREEMENT_XML XMLType )
         XMLTYPE COLUMN AGREEMENT_XML XMLSCHEMA "ABQuote_V1.xsd" ELEMENT "Quote"
              VARRAY AGREEMENT_XML.XMLDATA."SHIPPING_PARTIES"
                   STORE AS TABLE SHIPPING_PARTIES_NT
                   ((PRIMARY KEY (NESTED_TABLE_ID, ARRAY_INDEX) ENABLE))
              VARRAY AGREEMENT_XML.XMLDATA."SALES_OFFICE_CODES"."STRING_WRAPPERS"
                   STORE AS TABLE SALES_OFFICE_CODES_NT
              ((PRIMARY KEY (NESTED_TABLE_ID, ARRAY_INDEX) ENABLE))
         TABLESPACE RGM_ME_DATA;
    alter table TNMAB_AGREEMENT_XML
    add constraint TNM_AGREEMENT_XML_PK primary key (AGREEMENT_XML.XMLDATA."AGREEMENT_ID",
                                  AGREEMENT_XML.XMLDATA."AGREEMENT_VERSION")
    using index tablespace RGM_ME_INDX;
    We populated around 500K rows and have been seeing some Performance Issues
    in accessing data from above Table, at times.
    What is difference between extractValue and existsNode in terms of performance?
    Here are sample queries:
    SELECT extract(AGREEMENT_XML, '/') "Quote" FROM TNMAB_AGREEMENT_XML WHERE extractValue(AGREEMENT_XML, '/Quote/Identifier') = ‘00003554’
    SELECT extract(AGREEMENT_XML, '/') "Quote" FROM TNMAB_AGREEMENT_XML WHERE existsNode(AGREEMENT_XML, '/Quote[Identifier = "00003554"]') = 1
    Which of the above would be better to use existsNode or extractValue.
    In above case, both the queries are expected to return Single Row (searched
    using Quote Identifier, which is defined as PK of Table) and query explain plan does
    show usage of PK for above queries.
    Thanks
    user641521

    In theory existsNode can be slightly better, however in you cases the two queries are not identical.
    Also there are a number of other issues with your query..
    1. extract(AGREEMENT_XML, '/') is not required. You should just have the AGREEMENT_XML column. Extract is only need when extracting a fragment from the XML. Since you are returning the entire document the use of extract(column,'/') is redundant, but can cause performance issues..
    THis query should be written as
    SELECT AGREEMENT_XML "Quote"
    FROM TNMAB_AGREEMENT_XML
    WHERE extractValue(AGREEMENT_XML, '/Quote/Identifier') = ‘00003554’
    and can be written using existsNode as
    SELECT AGREEMENT_XML "Quote"
    FROM TNMAB_AGREEMENT_XML
    WHERE existsNode(AGREEMENT_XML, '/Quote[Identifier="00003554"]') = 1
    Assuming Identifier can only occur once inside Quote. If Identifier can occur multiple times inside Quote then the existsNode version would still work while the extractValue version would return errors

  • TAXINN AND TAXINJ difference ? AND Which is better ?

    HI,
      Could u please explain  difference between TAXINN AND TAXINJ  ? AND Which is better ? And in which scenario they are used ?
    Regrds,
    Binayak

    TAXINJ & TAXINN are Tax Procedures in India. TAXINJ is old version & TAX INN is new version. Both has its own advantage & disadvantage.
    Upto 4.6C & partially 4.7 version of SAP, TAXINJ was used. TAXINJ is formula based calculation, in which we maintain the tax rate in Tax Code itself. The implication is that if say we are having product range such that say Excise rate differes for separate chapter ID, VAT, CST & permutation & combination of these, we require that many Tax Codes. For example:
    Tax Code: A1
    Taxes: 16% Excise Duty + 2% Education Cess + 12% VAT
    Tax Code: A2
    Taxes: 16% Excise Duty + 2% Education Cess + 8% VAT
    Tax Code: A3
    Taxes: 12% Excise Duty + 2% Education Cess + 12% VAT
    Tax Code: A3
    Taxes: 12% Excise Duty + 2% Education Cess + 8% VAT
    From 4.7 version onwards of SAP, TAXINN is being recommended & used. TAXINN is more user friendly & condition record based. In TAXINN, Tax Codes are statistical & of not much relevance, but are required to be maintained in condition record for taxes condition type. This makes Tax Codes simpler. The implication is that if say we are having product range such that say Excise rate differes for separate chapter ID, VAT, CST, we need not have the tax codes to that combination. For example:
    Tax Code: A1
    Can be used for any rate of excise duty, as tax code is only required to be maintained statistically in condition record.
    Tax Code: A2
    Can be used for any rate of VAT, as tax code is only required to be maintained statistically in condition record
    Regards,
    Rajesh Banka
    Reward points if helpful.

  • Which gives better performance in webi using display attr or nav attr -

    Hello all,
    We are using the Bex query as the datasource for our universes and the end user is using the Web Intelligence as the reporting tool (rich client and infoview) we have employee as one of the infoobject in the cube.
    Now employee has a lot of attributes which the user wants to use for reporting (delivered employee infoobject has quite a few attr), we are making some of them as Nav attr like Org unit since they are time dependent and the end user will need to put in the key date to bring the employees from right org unit.
    We have enhanced the employee attr to have the all address information of the employee (Z fileds) and we have made those nav attr in RSd1.
    So my question is should we make the address Z fields as nav attr in cube as well and use those objects in webi or can we use the objects in webi which fall under employee like details (green icons) rather than separate object.
    Please let me know what will keep better performance and what is the best practice.
    Thanks you in advance and appreciate everyone's help
    Edited by: Cathy on Jun 16, 2011 7:35 AM

    Hi,
    BEx Query Design Recommendations:
    "Reduce Usage of Navigational Attributes as much as possible Also, if simply displaying a Characteristicu2019s Attribute, DO NOT use the Navigational Attribute u2013 rather utilize the Characteristic Attribute for display in the report  This avoids unneeded JOINS, and also reduces total number of rows transferred to WebI"
    Source : SAP Document
    Thanks,
    Amit

Maybe you are looking for