[git commit] grep: short-circuit -v to bail out on first match

Denys Vlasenko vda.linux at googlemail.com
Tue Jan 29 13:53:22 UTC 2019


commit: https://git.busybox.net/busybox/commit/?id=d4b568c108b89fb726181b0fabb19f2d62bc1930
branch: https://git.busybox.net/busybox/commit/?id=refs/heads/master

A small optimization. There is no need to try matching the current
input line against any further patterns if a match was already
found and -v is specified.

function                                             old     new   delta
grep_file                                           1463    1440     -23

Signed-off-by: Ari Sundholm <ari at tuxera.com>
Signed-off-by: Niko Vähäsarja <niko at tuxera.com>
Signed-off-by: Denys Vlasenko <vda.linux at googlemail.com>
---
 findutils/grep.c | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)

diff --git a/findutils/grep.c b/findutils/grep.c
index 9d9da422c..2cbe7ea91 100644
--- a/findutils/grep.c
+++ b/findutils/grep.c
@@ -443,15 +443,23 @@ static int grep_file(FILE *file)
 					}
 				}
 			}
-			/* If it's non-inverted search, we can stop
-			 * at first match */
-			if (found && !invert_search)
-				goto do_found;
+			/* If it's a non-inverted search, we can stop
+			 * at first match and report it.
+			 * If it's an inverted search, we can move on
+			 * to the next line of input, ignoring the
+			 * rest of the patterns.
+			 */
+			if (found) {
+				//if (invert_search)
+				//	goto do_not_found;
+				//goto do_found;
+				break; // this accomplishes both
+			}
 			pattern_ptr = pattern_ptr->link;
 		} /* while (pattern_ptr) */
 
 		if (found ^ invert_search) {
- do_found:
+ //do_found:
 			/* keep track of matches */
 			nmatches++;
 
@@ -552,6 +560,7 @@ static int grep_file(FILE *file)
 		}
 #if ENABLE_FEATURE_GREP_CONTEXT
 		else { /* no match */
+ //do_not_found:
 			/* if we need to print some context lines after the last match, do so */
 			if (print_n_lines_after) {
 				print_line(line, strlen(line), linenum, '-');


More information about the busybox-cvs mailing list