string reuse

Peter Rice pmr at ebi.ac.uk
Wed May 21 10:23:05 UTC 2003


raouljp at libero.it wrote:
> hi, 
> i have a question about reuse of AjPStr objects.
> 
> which of the two possibilities is it correct or better?
> 1) 
> str = ajStrNew();
> for ( i = 0; i < iMax; i++ )
>  {
>      ajStrAssSubC( &str, ajStrStr( text ), i, i+lenght_substring-1 );
>       ... 
>       ajStrDelReuse( &str);
> }
> ajStrDel( &str );
> 
> 2) 
> 
> for ( i = 0; i < iMax; i++ )
>  {
>      str = ajStrNew();
>      ajStrAssSubC( &str, ajStrStr( text ), i, i+lenght_substring-1 );
>       ... 
>       ajStrDel( &str);
> }

(1) Uses one string object, makes it longer if the new string is longer 
than the existing string reserved space, and deletes it at the end. it 
is very useful you expect a long string later.

You can extend this by picking a size for the string (using 
ajStrNewL(maxlength) instead of ajStrNew) to save some re-allocation.

But you do have the full length string in memory until you call ajStrDel.

(2) Creates a new string each time, and deletes it afterwards. If you 
are working with short strings it can be good.

In practice there is not much difference.

A minor philosophical point - ajStrNew does not allocate space for a 
string - it returns an extra reference-counted copy of the internal 
empty string. When you first use it, then it makes a new string.

Hope this helps,

Peter Rice




More information about the emboss-dev mailing list