Skip to content

Commit 35b8f99

Browse files
Havretrayokota
andauthored
Improve perf of base64 encoding check on a consumer hot path (#2371)
Co-authored-by: Robert Yokota <[email protected]>
1 parent 224a561 commit 35b8f99

File tree

2 files changed

+24
-21
lines changed

2 files changed

+24
-21
lines changed

src/Confluent.SchemaRegistry/CachedSchemaRegistryClient.cs

Lines changed: 4 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -593,34 +593,17 @@ private bool checkSchemaMatchesFormat(string format, string schemaString)
593593
// if a format isn't specified, then assume text is desired.
594594
if (format == null)
595595
{
596-
try
597-
{
598-
Convert.FromBase64String(schemaString);
599-
}
600-
catch (Exception)
601-
{
602-
return true; // Base64 conversion failed, infer the schemaString format is text.
603-
}
604-
605-
return false; // Base64 conversion succeeded, so infer the schamaString format is base64.
596+
// If schemaString is not Base64, infer the schemaString format is text.
597+
return !Utils.IsBase64String(schemaString);
606598
}
607599
else
608600
{
609601
if (format != "serialized")
610602
{
611603
throw new ArgumentException($"Invalid schema format was specified: {format}.");
612604
}
613-
614-
try
615-
{
616-
Convert.FromBase64String(schemaString);
617-
}
618-
catch (Exception)
619-
{
620-
return false;
621-
}
622-
623-
return true;
605+
606+
return Utils.IsBase64String(schemaString);
624607
}
625608
}
626609

src/Confluent.SchemaRegistry/Utils.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
using System.Linq;
2121
using Confluent.Kafka;
2222

23+
#if NET8_0_OR_GREATER
24+
using System.Buffers.Text;
25+
#endif
2326

2427
namespace Confluent.SchemaRegistry
2528
{
@@ -70,5 +73,22 @@ public static bool ListEquals<T>(IList<T> a, IList<T> b)
7073
if (a == null || b == null) return false;
7174
return a.SequenceEqual(b);
7275
}
76+
77+
internal static bool IsBase64String(string value)
78+
{
79+
#if NET8_0_OR_GREATER
80+
return Base64.IsValid(value);
81+
#else
82+
try
83+
{
84+
_ = Convert.FromBase64String(value);
85+
return true;
86+
}
87+
catch (FormatException)
88+
{
89+
return false;
90+
}
91+
#endif
92+
}
7393
}
7494
}

0 commit comments

Comments
 (0)