A lot of people tend to copy strings like this:
PHP код:
format(dest, sizeof (dest), "%s", src);
This is one of the worst ways to do it! I did timings on six different methods of copying strings, in all cases "b" is the destination and "a" is the source. "strcpy" is a hand written PAWN function to copy strings:
PHP код:
strmid(b, a, 0, strlen(a), sizeof (b));
format(b, sizeof (b), "%s", a);
b[0] = '\0';
strcat(b, a, sizeof (b));
memcpy(b, a, 0, strlen(a) * 4 + 4, sizeof (b)); // Length in bytes, not cells.
strcpy(b, a);
b = a;
Note that "b = a;" is the standard PAWN array copy and only works for arrays known at compile time to be the same size, or with a larger desination. Unfortunately I ran a range of tests and they do not point to a single best function. What they DO do is show quite clearly that both the hand coded PAWN version and format are very slow at copying strings:
For short strings in small arrays, "b = a;" is fastest when applicable, strcat with prior NULL termination (important) is second.
For short strings in large arrays, strcat is fastest.
For longer strings in longer arrays, "b = a;" is again fastest, with memcpy second.
For huge arrays "b = a;" seems to be fastest.
Where possible use standard array assignment, however this is not always possible, for example when a string of unknown size is passed to a function. In these cases I would suggest using strcat (if you're interested, note the bizzare syntax):
PHP код:
#define strcpy(%0,%1,%2) \
strcat((%0[0] = '\0', %0), %1, %2)
Use:
PHP код:
strcpy(dest, src, sizeof (dest));
|