From f92c5b96acb7057b1acbae6447de850ede1c094e Mon Sep 17 00:00:00 2001
From: "X.organic" <dilithium.no3@protonmail.com>
Date: Mon, 22 Aug 2022 13:25:24 +0200
Subject: [PATCH] Fix a performance regression in query functions

This commit brings back the old code for W_CheckNumForNamePwad, using memcmp
instead of strncmp, which is readily inlined by modern C compilers and has
more acceptable performance in P_AddWadFile. Also removes some redundant
strlens, saving the result of one call instead.

This commit increases this branch's distance from SRB2 2.2, per Ashnal
and SteelT's note that I shouldn't worry too much about it, especially
when there's performance on the line.
---
 src/w_wad.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/src/w_wad.c b/src/w_wad.c
index ce47b849d..3f6d0fd15 100644
--- a/src/w_wad.c
+++ b/src/w_wad.c
@@ -953,7 +953,8 @@ UINT16 W_CheckNumForNamePwad(const char *name, UINT16 wad, UINT16 startlump)
 	if (!TestValidLump(wad,0))
 		return INT16_MAX;
 
-	strlcpy(uname, name, sizeof uname);
+	memset(uname, 0, sizeof uname);
+	strncpy(uname, name, sizeof(uname)-1);
 	strupr(uname);
 
 	//
@@ -965,7 +966,7 @@ UINT16 W_CheckNumForNamePwad(const char *name, UINT16 wad, UINT16 startlump)
 	{
 		lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump;
 		for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++)
-			if (!strncmp(lump_p->name, uname, sizeof(uname) - 1))
+			if (memcmp(lump_p->name, uname, sizeof(uname) - 1) == 0)
 				return i;
 	}
 
@@ -1044,9 +1045,10 @@ UINT16 W_CheckNumForFolderEndPK3(const char *name, UINT16 wad, UINT16 startlump)
 {
 	INT32 i;
 	lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump;
+	size_t name_length = strlen(name);
 	for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++)
 	{
-		if (strnicmp(name, lump_p->fullname, strlen(name)))
+		if (strnicmp(name, lump_p->fullname, name_length))
 			break;
 	}
 	return i;
@@ -1058,9 +1060,10 @@ UINT16 W_CheckNumForFullNamePK3(const char *name, UINT16 wad, UINT16 startlump)
 {
 	INT32 i;
 	lumpinfo_t *lump_p = wadfiles[wad]->lumpinfo + startlump;
+	size_t name_length = strlen(name);
 	for (i = startlump; i < wadfiles[wad]->numlumps; i++, lump_p++)
 	{
-		if (!strnicmp(name, lump_p->fullname, strlen(name)))
+		if (!strnicmp(name, lump_p->fullname, name_length))
 		{
 			return i;
 		}
-- 
GitLab