Improve performance of strncpy

Message ID 000401cfbc74$758a9b80$609fd280$@com
State Superseded
Headers

Commit Message

Wilco Dijkstra Aug. 20, 2014, 12:44 p.m. UTC
  Hi,

This patch improves strncpy performance by using memset to clear memory after the string when the
buffer is much larger than the copied string. This is better as memset is significantly faster than
a simple byte-loop. On bench-strncpy it is ~25% faster.

ChangeLog:
2014-08-20  Wilco Dijkstra  <wdijkstr@arm.com>

	* string/strncpy.c (strncpy): Improve performance by using memset.
---
 string/strncpy.c |    9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
  

Comments

Adhemerval Zanella Netto Aug. 22, 2014, 12:02 p.m. UTC | #1
On 20-08-2014 09:44, Wilco Dijkstra wrote:
> Hi,
>
> This patch improves strncpy performance by using memset to clear memory after the string when the
> buffer is much larger than the copied string. This is better as memset is significantly faster than
> a simple byte-loop. On bench-strncpy it is ~25% faster.

Hi, the patch looks ok. I also pushed a similar modification for powerpc based on same idea. 

>
> ChangeLog:
> 2014-08-20  Wilco Dijkstra  <wdijkstr@arm.com>
>
> 	* string/strncpy.c (strncpy): Improve performance by using memset.
> ---
>  string/strncpy.c |    9 ++++++---
>  1 file changed, 6 insertions(+), 3 deletions(-)
>
> diff --git a/string/strncpy.c b/string/strncpy.c
> index 0915e03..604417c 100644
> --- a/string/strncpy.c
> +++ b/string/strncpy.c
> @@ -78,9 +78,12 @@ STRNCPY (char *s1, const char *s2, size_t n)
>    while (c != '\0');
>  
>   zero_fill:
> -  do
> -    *++s1 = '\0';
> -  while (--n > 0);
> +  if (n >= 8)
> +    memset (s1 + 1, '\0', n);
> +  else
> +    do
> +      *++s1 = '\0';
> +    while (--n > 0);

I wonder if this test is really worth, my opinion is just to keep it simple
and just call memset on both 'goto' in loop and after 'last_chars'.

>  
>    return s;
>  }
> -- 1.7.9.5
  

Patch

diff --git a/string/strncpy.c b/string/strncpy.c
index 0915e03..604417c 100644
--- a/string/strncpy.c
+++ b/string/strncpy.c
@@ -78,9 +78,12 @@  STRNCPY (char *s1, const char *s2, size_t n)
   while (c != '\0');
 
  zero_fill:
-  do
-    *++s1 = '\0';
-  while (--n > 0);
+  if (n >= 8)
+    memset (s1 + 1, '\0', n);
+  else
+    do
+      *++s1 = '\0';
+    while (--n > 0);
 
   return s;
 }