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

[PATCH] builtins: search builtin commands via binary search.

From
Stefan Beller <stefanbeller@googlemail.com>
Date
Jul 27, 2013, 08:50 UTC
Message-ID
<1374915038-6717-1-git-send-email-stefanbeller@googlemail.com>
In-Reply-To
<51F38997.9010507@googlemail.com>

There are currently 115 commands built into the git executable. Before this commit, it was iterated over these commands in a linear order, i.e. each command was checked.

As it turns out the commands are already sorted alphabetically, it is easy to perform a binary search instead of linear searching. This results in 7 lookups in the worst case.

Signed-off-by: Stefan Beller <stefanbeller@googlemail.com>
---
 git.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
diff --git a/git.c b/git.c
index 2025f77..6d4de2b 100644
--- a/git.c
+++ b/git.c
@@ -309,9 +309,14 @@ static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
 	return 0;
 }
 
+static int compare_internal_command(const void *name, const void *cmd) {
+	return strcmp((const char*)name, ((const struct cmd_struct*)cmd)->cmd);
+}
+
 static void handle_internal_command(int argc, const char **argv)
 {
 	const char *cmd = argv[0];
+	/* commands must be sorted alphabetically for binary search */
 	static struct cmd_struct commands[] = {
 		{ "add", cmd_add, RUN_SETUP | NEED_WORK_TREE },
 		{ "annotate", cmd_annotate, RUN_SETUP },
@@ -447,12 +452,12 @@ static void handle_internal_command(int argc, const char **argv)
 		argv[0] = cmd = "help";
 	}
 
-	for (i = 0; i < ARRAY_SIZE(commands); i++) {
-		struct cmd_struct *p = commands+i;
-		if (strcmp(p->cmd, cmd))
-			continue;
+	struct cmd_struct *p = bsearch(cmd, commands,
+				ARRAY_SIZE(commands), sizeof(struct cmd_struct),
+				compare_internal_command);
+
+	if (p)
 		exit(run_builtin(p, argc, argv));
-	}
 }
 
 static void execv_dashed_external(const char **argv)
-- 
1.8.4.rc0.1.g8f6a3e5
Previous: Stefan BellerNext: Andreas Schwab
Message 4 of 8 in “builtins: search builtin commands via binary search.”
  1. builtins: search builtin commands via binary search.Stefan Beller, Jul 26, 2013
  2. Jonathan NiederJul 26, 2013
  3. Stefan BellerJul 27, 2013
  4. builtins: search builtin commands via binary search.Stefan Beller, Jul 27, 2013
  5. Andreas SchwabJul 27, 2013
  6. Eric SunshineJul 28, 2013
  7. Junio C HamanoJul 29, 2013
  8. Eric SunshineJul 27, 2013

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.