www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Freeing memory after string concatenation

reply Alex <a_bothe gmx.net> writes:
Hey,
I got a problem after concatenating two strings:

void main()
{
       while(true) // For faking high program activity...
       {
             string t="Do";
             string t2="That"
             
             foo(t,t2);

             delete t;
             delete t2;
       }
}

void foo(string s1, string s2)
{
       string con=s1~s2;
       writeln(con);
       delete con;
}

until now, there seems everything to be ok but now I want to make my program
run most efficiently...
I looked at the memory usage with the TaskManager
I found that 'con' did not get removed! (the memory usage grew up very fast
after several repeations)

Why?
Dec 23 2008
next sibling parent bearophile <bearophileHUGS lycos.com> writes:
I am using D1, while you probably use D2. I have compiled the following code
with -O -release -inline, with the last DMD 1.x:


import std.stdio: writefln;

void foo(string s1, string s2) {
    string con = s1 ~ s2;
    writefln(con);
}

void main() {
    while(true) {
        string t1 = "Do";
        string t2 = "That";
        foo(t1, t2);
    }
}

After more than two minutes of running I don't see any increase of memory used.
Don't use delete in your code, generally it's not needed.

Bye,
bearophile
Dec 23 2008
prev sibling parent Sean Kelly <sean invisibleduck.org> writes:
Alex wrote:
 Hey,
 I got a problem after concatenating two strings:
 
 void main()
 {
        while(true) // For faking high program activity...
        {
              string t="Do";
              string t2="That"
              
              foo(t,t2);
 
              delete t;
              delete t2;
Not necessary in this case, since t and t2 will reference static memory.
        }
 }
 
 void foo(string s1, string s2)
 {
        string con=s1~s2;
        writeln(con);
        delete con;
Here, a single allocation will take place for con.
 }
 
 until now, there seems everything to be ok but now I want to make my program
run most efficiently...
 I looked at the memory usage with the TaskManager
 I found that 'con' did not get removed! (the memory usage grew up very fast
after several repeations)
You can't watch TaskManager to get an accurate measure of in-program memory use. The GC allocates and potentially frees memory from the OS in blocks, and it does not do so very often. Better to use the GC statistics feature if you want a detailed idea of what's going on. Sean
Dec 23 2008