bug-coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Expr: Improvement of substr


From: Sebastian Kreft
Subject: Expr: Improvement of substr
Date: Sun, 10 Sep 2006 18:43:01 -0400

Hi, I was playing around with expr and I noticed that when you execute the
following
%>expr substr hello 1 700000000
it takes to long to output the answer.

%>time expr substr hello 1 700000000
hello

real    0m27.745s
user    0m0.828s
sys     0m1.220s

So I looked the source code and noticed that you were creating a new string
of size 700000000, so lot of memory is used.
And also strncpy takes long time filling the rest of the string with nulls.

So I add a few lines that check if the desired length is suitable and if not
then changes the length to the maximum possible.

Here are the results
%>time ./expr substr hello 1 700000000
hello

real    0m0.097s
user    0m0.000s
sys     0m0.008s

Here is the diff between the files
--- expr_old.c  2006-09-10 18:02:47.000000000 -0400
+++ expr.c      2006-09-10 18:26:34.000000000 -0400
@@ -551,16 +551,20 @@
    }
  else if (nextarg ("substr"))
    {
+      int length;
      l = eval6 (evaluate);
      i1 = eval6 (evaluate);
      i2 = eval6 (evaluate);
      tostring (l);
+      length = strlen (l->u.s);
      if (!toarith (i1) || !toarith (i2)
-         || strlen (l->u.s) < i1->u.i
+         || length < i1->u.i
         || i1->u.i <= 0 || i2->u.i <= 0)
       v = str_value ("");
      else
       {
+         if(i2->u.i + i1->u.i - 1 > length)
+            i2->u.i = length - i1->u.i + 1;
         v = xmalloc (sizeof *v);
         v->type = string;
         v->u.s = strncpy (xmalloc (i2->u.i + 1),



Sebastián Kreft C.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]