I have to write fast right-trimming function in C. My first attempt to do it was:
void TrimRight( char *s )
{
char* pS;
if (!*s)
return;
if (!s)
return;
for ( pS = s + strlen(s) - 1; isspace(*pS) && (pS >= s); pS--)
{
pS[1] = '\0';
}
}
Second attempt:
void TrimRight( char *s )
{
if (!*s)
return;
if (!s)
return;
char* pS = s + strlen(s) - 1;
while ((*pS == ' ') && (pS > s))
{
(*pS--) = '\0';
}
}
The question is: Did I improve memory accesses here? How can I optimize this even more? How to optimize memory access in general?
Upd: Is it true that scanning memory in increasing sequential order is faster?
I wouldn’t bother with the tests at the beginning. It should be a requirement of the function that a valid string be passed, which obviates the
!stest, and the!*sis redundant (Besides, placing the!stest second means you’ll crash first on the!*s). Also, you can avoid scanning in both directions (thestrlenscans one way, the while loop goes the other way) by keeping track of the last non-whitespace character:EDIT: Note that strlen might be faster than scanning for spaces (see comments).