git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH 3/3] grep: avoid one strdup() per file

From
Rasmus Villemoes <rv@rasmusvillemoes.dk>
Date
Feb 15, 2018, 21:56 UTC
Message-ID
<20180215215615.21208-4-rv@rasmusvillemoes.dk>
In-Reply-To
<20180215215615.21208-1-rv@rasmusvillemoes.dk>

There is only one instance of grep_source_init(GREP_SOURCE_FILE), and in that case the path and identifier arguments are equal - not just as strings, but the same pointer is passed. So we can save some time and memory by reusing the gs->path = xstrdup_or_null(path) we have already done as gs->identifier, and changing grep_source_clear accordingly to avoid a double free.

Signed-off-by: Rasmus Villemoes <rv@rasmusvillemoes.dk>
---
 grep.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/grep.c b/grep.c
index 3d7cd0e96..b1532b1b6 100644
--- a/grep.c
+++ b/grep.c
@@ -1972,7 +1972,8 @@ void grep_source_init(struct grep_source *gs, enum grep_source_type type,
 
 	switch (type) {
 	case GREP_SOURCE_FILE:
-		gs->identifier = xstrdup(identifier);
+		gs->identifier = identifier == path ?
+			gs->path : xstrdup(identifier);
 		break;
 	case GREP_SOURCE_OID:
 		gs->identifier = oiddup(identifier);
@@ -1986,7 +1987,10 @@ void grep_source_init(struct grep_source *gs, enum grep_source_type type,
 void grep_source_clear(struct grep_source *gs)
 {
 	FREE_AND_NULL(gs->name);
-	FREE_AND_NULL(gs->path);
+	if (gs->path == gs->identifier)
+		gs->path = NULL;
+	else
+		FREE_AND_NULL(gs->path);
 	FREE_AND_NULL(gs->identifier);
 	grep_source_clear_data(gs);
 }
-- 
2.15.1
Previous: Junio C HamanoNext: Jeff King
Message 5 of 12 in “a few grep patches”
  1. 0/3 a few grep patchesRasmus Villemoes, Feb 15, 2018
  2. 1/3 grep: move grep_source_init outside critical sectionRasmus Villemoes, Feb 15, 2018
  3. Jeff KingFeb 15, 2018
  4. Junio C HamanoFeb 16, 2018
  5. 3/3 grep: avoid one strdup() per fileRasmus Villemoes, Feb 15, 2018
  6. Jeff KingFeb 15, 2018
  7. 2/3 grep: simplify grep_oid and grep_fileRasmus Villemoes, Feb 15, 2018
  8. Brandon WilliamsFeb 15, 2018
  9. 0/2 two small grep patchesRasmus Villemoes, Feb 23, 2018
  10. 2/2 grep: simplify grep_oid and grep_fileRasmus Villemoes, Feb 23, 2018
  11. 1/2 grep: move grep_source_init outside critical sectionRasmus Villemoes, Feb 23, 2018
  12. Jeff KingFeb 23, 2018

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.