From e8bbbff659ca912f2d7fb05539f29c4a1444a2ba Mon Sep 17 00:00:00 2001 From: andreas hilti Date: Sat, 25 May 2024 20:49:46 +0200 Subject: [PATCH] improve merge performance Signed-off-by: andreas hilti --- src/CycloneDX.Utils/Merge.cs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/CycloneDX.Utils/Merge.cs b/src/CycloneDX.Utils/Merge.cs index da18352c..e3b17340 100644 --- a/src/CycloneDX.Utils/Merge.cs +++ b/src/CycloneDX.Utils/Merge.cs @@ -31,12 +31,33 @@ public List Merge(List list1, List list2) if (list2 is null) return list1; var result = new List(list1); + // We want to avoid the costly computation of the hashes if possible. + // Therefore, we use a nullable type. + var resultHashes = new List(list1.Count); + for (int i = 0; i < list1.Count; i++) resultHashes.Add(null); foreach (var item in list2) { - if (!(result.Contains(item))) + int hash = item.GetHashCode(); + bool found = false; + for (int i=0; i < result.Count; i++) + { + var resultItem = result[i]; + if (resultHashes[i] == null) + { + resultHashes[i] = resultItem.GetHashCode(); + } + int resultHash = resultHashes[i].Value; + if (hash == resultHash && item.Equals(resultItem)) + { + found = true; + break; + } + } + if (!found) { result.Add(item); + resultHashes.Add(hash); } }