Results 1 to 4 of 4

Thread: Which is Better

  1. #1
    Join Date
    Aug 2007
    Posts
    275
    Thanks
    28
    Thanked 2 Times in 2 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default Which is Better

    In case
    Qt Code:
    1. //style A
    2.  
    3. for ( int i = 0 ; i < 1000 ; ++i)
    4. {
    5. MyData data = getData();
    6. // do something with data
    7. }
    8.  
    9. //style B
    10. MyData data;
    11. for ( int i = 0 ; i < 1000 ; ++i)
    12. {
    13. data = getData();
    14. // do something with data
    15. }
    To copy to clipboard, switch view to plain text mode 

    Would I gain a little speed using A or B?,
    Which is one is more readable?

    have a good weekend,
    baray98

  2. #2
    Join Date
    Dec 2006
    Posts
    849
    Thanks
    6
    Thanked 163 Times in 151 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: Which is Better

    I would prefer A for readability. If the compiler properly uses RVO (return value optimization) it might be faster, too.

  3. #3
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,368
    Thanks
    3
    Thanked 5,017 Times in 4,793 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: Which is Better

    The speed might be different depending if you have copy constructor and assignment operators defined for your class. But in general the speed difference is so small you can ignore it.
    Your biological and technological distinctiveness will be added to our own. Resistance is futile.

    Please ask Qt related questions on the forum and not using private messages or visitor messages.


  4. #4
    Join Date
    Sep 2008
    Posts
    18
    Thanks
    2
    Thanked 3 Times in 3 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: Which is Better

    If the variable "data" is only going to be used in the loop then definitely style A. If it's going to be used outside, you don't have a choice anyway. I don't see a reason to put variables into wider scope than necessary, you need to keep track of it longer which hurts readability rather than helps.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.