Results 1 to 6 of 6

Thread: which is more effective?

  1. #1

    Thread Starter
    <?="Moderator"?> john tindell's Avatar
    Join Date
    Jan 2002
    Location
    Brighton, UK
    Posts
    1,099

    which is more effective?

    which method is more effective, or faster, well better.

    Code:
    cout<<"line 1"<<endl<<"line 2";
    or

    Code:
    cout<<"line 1\nline 2";

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    The second is faster.

    Not only is it less function calls, it also has the newline embedded.

    The main kicker, though, is the non-use of endl. That actually outputs a newline, then flushes the stream.
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    Therefore the second makes more efficient use of the buffer.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  4. #4
    Guru Yonatan's Avatar
    Join Date
    Apr 1999
    Location
    Israel
    Posts
    892
    ...But they slightly differ in their effect.
    Try putting a getch(); after each one (assuming you use VC++) and testing them separately.

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    They do, but if one of the effects is unwanted then the other most probably is too. And you shouldn't rely on that.

    Anyway:
    cout<<"line 1"<<endl<<"line 2"<<endl;
    and
    cout<<"line 1\nline 2"<<endl;

    have exactly the same effect with the second being much better.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  6. #6
    Guru Yonatan's Avatar
    Join Date
    Apr 1999
    Location
    Israel
    Posts
    892
    Or just call cout.flush(); if you don't want the '\n' to be printed.
    Code:
    cout << endl;
    // is the same as
    cout << '\n';
    cout.flush();

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width