Thread: Clearing a string

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    Clearing a string

    Lets say i need a c++ string to be cleared in a loop each looping.

    Which one is better?

    N°1
    Code:
        for(j=0; j<=9; j++)    
        {
             string   current;        
             current+= dataset[array[j]];
        }
    N°2
    Code:
         string   current; 
         for(j=0; j<=9; j++)    
         {
             string = "";        
             current+= dataset[array[j]];
         }
    I think about the second because the string wont get declared everytime but maybe its the same?
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    I would prefer the second one if you actually plan on using the string outside the for loop. And you can use clear() to clear the string instead of using the assignment operator.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I think it might also make sense to use string.clear() if you are not going to use it after the loop. Avoiding creating expensive objects within a loop is a kind of optimization that you can do as you go along, since unlike many other premature optimizations, it doesn't particularly affect the readability and quality of the code.

    Of course, it is also possible that this code is not called very often, and the strings in question will not be particularly large, so it really won't affect the observable performance of the program in any way, in which case you might stop worrying and follow the rule-of-thumb that the scope of variables should be limited to where they are used.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Hmm, interesting, thank you Memloop and Anon!

    Actually it will be called more than a 1000 times so i guess ill be better off with string.clear().

    Otherwise it would be declared a 1000 times on the stack as i understand.
    Using Windows 10 with Code Blocks and MingW.

  5. #5
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Declaring something on the stack is a small problem. The larger problem is that for each of the 10 iterations, the string object declared in the loop would have to deallocate any dynamic memory, and allocate new memory for the next iteration. That's where the expense of a std::string comes from.

    The clear method only marks the string internally as empty, but doesn't actually deallocate any memory. The capacity remains the same, and during the next iteration the same memory can be reused.

    Another hidden cost might be if the string dynamically grows during the iteration. If you keep the same instance, it is quite likely that it grows to a sufficient size already during the first iteration, which means that any reallocations would be avoided during the following iterations.

    (This applies to MingW's implementation of std::string.)
    Last edited by anon; 12-03-2009 at 08:18 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> it doesn't particularly affect the readability and quality of the code

    I disagree with this. I seriously doubt that there would be any slowdown if you declare it inside the loop, especially with only 1000 calls. Your compiler might be able to optimize that anyway.

    However, I do believe there is a difference in readability and code quality. The first option makes it clear that the string is only used inside the loop. That means it is more readable. It also prevents accidental usage later in the function (maybe not such a problem in this example, but it could be in general). That makes it better quality.

    So I'd pick #1 and I'd consider #2 to be a premature optimization unless there is an obvious slowdown and the loop is called a significant number of times.

  7. #7
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Well, you might be right. There is indeed often no need to squeeze out performance (and running this loop 1000 times might not be much indeed).

    However, I think it is important to be aware of such issues (and I don't trust the compiler to be able to optimize such complicated operations - I suspect that it wouldn't even be legal for it to optimize constructors/destructors away in such contexts?).

    Code:
    #include <string>
    #include <ctime>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        clock_t start = clock();
    
        for (unsigned i = 0; i != 50000; ++i) {
            //string s;
            for (unsigned j = 0; j != 10; ++j) {
                string s;
                //s.clear();
                s += "Hello world";
                s += "Goodbye world!";
                s += "abcdefghijklmnopqrstuvwxyz";
            }
        }
        std::cout << clock() - start << '\n';
    }
    That's a really rough test. But depending on where the string is declared, my times are 328 and 796.

    However, note that this is called 50000 times, with 1000 times the difference wouldn't even be measurable.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM