summaryrefslogtreecommitdiff
path: root/string/strtok_r.c
diff options
context:
space:
mode:
authorWilco Dijkstra <wdijkstr@arm.com>2016-12-14 15:12:18 +0000
committerWilco Dijkstra <wdijkstr@arm.com>2016-12-14 15:12:18 +0000
commitd58ab810a6e325cc351684d174c48cabce01bcc1 (patch)
tree52a582dd886d5931988c3a6e2d1acd79efe2fe33 /string/strtok_r.c
parent14348aaeff5ccb136e3fe967b86f97b9cea950a2 (diff)
Improve strtok and strtok_r performance. Instead of calling strpbrk which
calls strcspn, call strcspn directly so we get the end of the token without an extra call to rawmemchr. Also avoid an unnecessary call to strcspn after the last token by adding an early exit for an empty string. Change strtok to tailcall strtok_r to avoid unnecessary code duplication. Remove the special header optimization for strtok_r of a 1-character constant string - both strspn and strcspn contain optimizations for this case. Benchmarking this showed similar performance in the worst case, but up to 5.5x better performance in the "found" case for large inputs. * benchtests/bench-strtok.c (oldstrtok): Add old implementation. * string/strtok.c (strtok): Change to tailcall __strtok_r. * string/strtok_r.c (__strtok_r): Optimize for performance. * string/string-inlines.c (__old_strtok_r_1c): New function. * string/bits/string2.h (__strtok_r): Move to string-inlines.c.
Diffstat (limited to 'string/strtok_r.c')
-rw-r--r--string/strtok_r.c31
1 files changed, 16 insertions, 15 deletions
diff --git a/string/strtok_r.c b/string/strtok_r.c
index f351304766..2d251f90d7 100644
--- a/string/strtok_r.c
+++ b/string/strtok_r.c
@@ -22,14 +22,10 @@
#include <string.h>
-#undef strtok_r
-#undef __strtok_r
-
#ifndef _LIBC
/* Get specification. */
# include "strtok_r.h"
# define __strtok_r strtok_r
-# define __rawmemchr strchr
#endif
/* Parse S into tokens separated by characters in DELIM.
@@ -45,11 +41,17 @@
char *
__strtok_r (char *s, const char *delim, char **save_ptr)
{
- char *token;
+ char *end;
if (s == NULL)
s = *save_ptr;
+ if (*s == '\0')
+ {
+ *save_ptr = s;
+ return NULL;
+ }
+
/* Scan leading delimiters. */
s += strspn (s, delim);
if (*s == '\0')
@@ -59,18 +61,17 @@ __strtok_r (char *s, const char *delim, char **save_ptr)
}
/* Find the end of the token. */
- token = s;
- s = strpbrk (token, delim);
- if (s == NULL)
- /* This token finishes the string. */
- *save_ptr = __rawmemchr (token, '\0');
- else
+ end = s + strcspn (s, delim);
+ if (*end == '\0')
{
- /* Terminate the token and make *SAVE_PTR point past it. */
- *s = '\0';
- *save_ptr = s + 1;
+ *save_ptr = end;
+ return s;
}
- return token;
+
+ /* Terminate the token and make *SAVE_PTR point past it. */
+ *end = '\0';
+ *save_ptr = end + 1;
+ return s;
}
#ifdef weak_alias
libc_hidden_def (__strtok_r)