git.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH] builtins: search builtin commands via binary search.
@ 2013-07-26 20:50 Stefan Beller
  2013-07-26 20:57 ` Jonathan Nieder
  2013-07-27  0:26 ` Eric Sunshine
  0 siblings, 2 replies; 8+ messages in thread
From: Stefan Beller @ 2013-07-26 20:50 UTC (permalink / raw)
  To: git; +Cc: Stefan Beller

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 | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)

diff --git a/git.c b/git.c
index 2025f77..0d7a9b5 100644
--- a/git.c
+++ b/git.c
@@ -309,9 +309,18 @@ static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
 	return 0;
 }
 
+static int compare_internal_command(const void *a, const void *b) {
+	/* The first parameter is of type char* describing the name,
+	   the second is a struct cmd_struct */
+	const char *name = (const char*)a;
+	const struct cmd_struct *cmd_struct = (struct cmd_struct*)b;
+	return strcmp(name, cmd_struct->cmd);
+}
+
 static void handle_internal_command(int argc, const char **argv)
 {
 	const char *cmd = argv[0];
+	/* commands must be sorted alphabetically */
 	static struct cmd_struct commands[] = {
 		{ "add", cmd_add, RUN_SETUP | NEED_WORK_TREE },
 		{ "annotate", cmd_annotate, RUN_SETUP },
@@ -447,12 +456,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 = (struct cmd_struct *)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

^ permalink raw reply related	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2013-07-29 16:18 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2013-07-26 20:50 [PATCH] builtins: search builtin commands via binary search Stefan Beller
2013-07-26 20:57 ` Jonathan Nieder
2013-07-27  8:49   ` Stefan Beller
2013-07-27  8:50     ` Stefan Beller
2013-07-27  9:13     ` Andreas Schwab
2013-07-28  9:05     ` Eric Sunshine
2013-07-29 16:18     ` Junio C Hamano
2013-07-27  0:26 ` Eric Sunshine

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).