Skip to content

Commit 6cdaaf2

Browse files
committed
perf: use of Span instead of string split
1 parent e7f96a9 commit 6cdaaf2

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

src/FileSizeFromBase64.NET/FileSizeHelpers.cs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,18 @@ public static class FileSizeHelpers
1717
public static double GetFileSizeFromBase64String(string base64String, bool applyPaddingsRules = false, UnitsOfMeasurement unitsOfMeasurement = UnitsOfMeasurement.Byte)
1818
{
1919
if (string.IsNullOrEmpty(base64String)) return 0;
20-
21-
// Remove MIME-type from the base64 string if exists and get the string length
22-
var base64Length = base64String.Contains("base64,") ? base64String.Split(',')[1].Length : base64String.Length;
23-
20+
21+
var base64Length = base64String.AsSpan().Slice(base64String.IndexOf(',') + 1).Length;
22+
2423
var fileSizeInByte = Math.Ceiling((double)base64Length / 4) * 3;
25-
26-
if(applyPaddingsRules && base64Length >= 2)
27-
{
28-
var paddings = base64String[^2..];
29-
fileSizeInByte = paddings.Equals("==") ? fileSizeInByte - 2 : paddings[1].Equals("=") ? fileSizeInByte - 1 : fileSizeInByte;
24+
25+
if (applyPaddingsRules && base64Length >= 2)
26+
{
27+
var paddings = base64String.AsSpan()[^2..];
28+
fileSizeInByte = paddings.EndsWith("==") ? fileSizeInByte - 2 :
29+
paddings[1].Equals('=') ? fileSizeInByte - 1 : fileSizeInByte;
3030
}
31-
32-
return (fileSizeInByte > 0) ? fileSizeInByte / (int)unitsOfMeasurement : 0;
31+
return fileSizeInByte > 0 ? fileSizeInByte / (int)unitsOfMeasurement : 0;
3332
}
3433
}
3534

0 commit comments

Comments
 (0)