Re: Which is the best way...

From: Chris Gilbert (chris@buzzbee.freeserve.co.uk)
Date: 08/16/99


Chuck Carson wrote:
>
> When you are adding to a buffer before sending it to the
> character, which is the more suitable method?
>
> 1)
>
> sprintf (buf + strlen(buf), "blah.....");
>
> or 2)
>
> sprintf(buf, "%sblah......", buf);
>
> Or do these two end up the same at the binary level
> anyway?

The 1st is the better as it only does a read (strlen counts till it hits
a 0 byte)  whereas sprintf should (in theory, unless someone's cunningly
optimised it) do a read and then a write of everything in buf back to
buf.  IE it strlen just does x reads, sprintf will do x reads and
writes, this takes up CPU/memory cycles.

If you really want to save/optimise and you're doing lots of sprintf's
one after the other this is the best in terms of cycles, as sprintf
returns the number of bytes written, and len will be kept in a CPU
register (if the compiler has any sense):

int len = 0;
len = sprintf(buf, "first thing");
len = sprintf(buf + len, "2nd thing");
len = sprintf(buf + len, "3rd thing");
sprintf(buf + len, "the last thing");

Although I think I've seen a few places where the code has changed from
the above style to use strlen(buf) style.

Chris


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     |  http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html  |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST