Skip to content

Commit 8c8f0f5

Browse files
authored
Reduce string allocations in sys helpers (#1644)
Apply string interpolation and span-based trimming updates under src/SIPSorcery/sys. Keep the KeyValuePair deconstruction helper because current transaction code still depends on it.
1 parent 2a93538 commit 8c8f0f5

5 files changed

Lines changed: 30 additions & 30 deletions

File tree

src/SIPSorcery/sys/Crypto/Crypto.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ private static FileStream GetFileStream(string filepath)
293293
if (!File.Exists(filepath))
294294
{
295295
logger.LogError("Cannot open a non-existent file for a hash operation, {FilePath}.", filepath);
296-
throw new IOException("Cannot open a non-existent file for a hash operation, " + filepath + ".");
296+
throw new IOException($"Cannot open a non-existent file for a hash operation, {filepath}.");
297297
}
298298

299299
// Open the file.
@@ -303,7 +303,7 @@ private static FileStream GetFileStream(string filepath)
303303
{
304304
inputStream.Close();
305305
logger.LogError("Cannot perform a hash operation on an empty file, {FilePath}.", filepath);
306-
throw new IOException("Cannot perform a hash operation on an empty file, " + filepath + ".");
306+
throw new IOException($"Cannot perform a hash operation on an empty file, {filepath}.");
307307
}
308308

309309
return inputStream;

src/SIPSorcery/sys/Crypto/PasswordHash.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,15 @@ public static string GenerateSalt(int? explicitIterations = null)
4242
{
4343
if (explicitIterations.HasValue && explicitIterations.Value < RFC289_MINIMUM_ITERATIONS)
4444
{
45-
throw new ArgumentException("Cannot be less than " + RFC289_MINIMUM_ITERATIONS, "explicitIterations");
45+
throw new ArgumentException($"Cannot be less than {RFC289_MINIMUM_ITERATIONS}", "explicitIterations");
4646
}
4747

4848
byte[] salt = new byte[SALT_SIZE];
4949
_randomProvider.GetBytes(salt);
5050

5151
var iterations = (explicitIterations ?? RFC289_MINIMUM_ITERATIONS).ToString("X");
5252

53-
return iterations + "." + Convert.ToBase64String(salt);
53+
return $"{iterations}.{Convert.ToBase64String(salt)}";
5454
}
5555

5656
/// <summary>

src/SIPSorcery/sys/Formatting/NumberFormatting.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,22 @@ public static string ToSIFormat(double number, int decimalPlaces)
2525
if (number > 1000000000000)
2626
{
2727
double teraNumber = Math.Round((double)(number / (double)100000000000), decimalPlaces);
28-
return teraNumber.ToString() + "T";
28+
return $"{teraNumber}T";
2929
}
3030
if (number > 1000000000)
3131
{
3232
double gigaNumber = Math.Round((double)(number / (double)100000000), decimalPlaces);
33-
return gigaNumber.ToString() + "G";
33+
return $"{gigaNumber}G";
3434
}
3535
else if (number > 1000000)
3636
{
3737
double kiloNumber = Math.Round((double)(number / (double)1000000), decimalPlaces);
38-
return kiloNumber.ToString() + "M";
38+
return $"{kiloNumber}M";
3939
}
4040
else if (number > 1000)
4141
{
4242
double kiloNumber = Math.Round((double)(number / (double)1000), decimalPlaces);
43-
return kiloNumber.ToString() + "k";
43+
return $"{kiloNumber}k";
4444
}
4545
else
4646
{
@@ -53,26 +53,26 @@ private static string ToSIByteFormat(double number, int decimalPlaces, string su
5353
if (number > 1099511627776)
5454
{
5555
double teraNumber = Math.Round((double)(number / (double)1099511627776), decimalPlaces);
56-
return teraNumber.ToString() + "T" + suffix;
56+
return $"{teraNumber}T{suffix}";
5757
}
5858
if (number > 1073741824)
5959
{
6060
double gigaNumber = Math.Round((double)(number / (double)1073741824), decimalPlaces);
61-
return gigaNumber.ToString() + "G" + suffix;
61+
return $"{gigaNumber}G{suffix}";
6262
}
6363
else if (number > 1048576)
6464
{
6565
double kiloNumber = Math.Round((double)(number / (double)1048576), decimalPlaces);
66-
return kiloNumber.ToString() + "M" + suffix;
66+
return $"{kiloNumber}M{suffix}";
6767
}
6868
else if (number > 1024)
6969
{
7070
double kiloNumber = Math.Round((double)(number / (double)1024), decimalPlaces);
71-
return kiloNumber.ToString() + "K" + suffix;
71+
return $"{kiloNumber}K{suffix}";
7272
}
7373
else
7474
{
75-
return Math.Round((double)number, decimalPlaces).ToString() + suffix;
75+
return $"{Math.Round((double)number, decimalPlaces)}{suffix}";
7676
}
7777
}
7878

src/SIPSorcery/sys/Net/IPSocket.cs

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,10 @@ public class IPSocket
4444
/// </summary>
4545
public static string GetSocketString(IPEndPoint endPoint)
4646
{
47-
string format = (endPoint.Address.AddressFamily == AddressFamily.InterNetworkV6) ? "[{0}]:{1}" : "{0}:{1}";
48-
return string.Format(format, endPoint.Address.ToString(), endPoint.Port.ToString(NumberFormatInfo.InvariantInfo));
47+
var address = endPoint.Address.ToString();
48+
var port = endPoint.Port.ToString(NumberFormatInfo.InvariantInfo);
49+
50+
return endPoint.Address.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{address}]:{port}" : $"{address}:{port}";
4951
}
5052

5153
/// <summary>
@@ -123,7 +125,7 @@ public static string ParseHostFromSocket(string socket)
123125
{
124126
string host = socket;
125127

126-
if (socket != null && socket.Trim().Length > 0 && socket.IndexOf(':') != -1)
128+
if (!string.IsNullOrWhiteSpace(socket) && socket.IndexOf(':') != -1)
127129
{
128130
host = socket.Substring(0, socket.LastIndexOf(':')).Trim();
129131
}
@@ -154,14 +156,14 @@ public static int ParsePortFromSocket(string socket)
154156
}
155157
// Look to see if this is IPv4 with a port (IPv6 will have another colon)
156158
// If it's a host name there will also not be another ':'.
157-
else if (socket.Substring(0, lastColonPos).LastIndexOf(':') != -1)
159+
else if (socket.AsSpan(0, lastColonPos).LastIndexOf(':') != -1)
158160
{
159161
// This is an IPv6 address WITHOUT a port.
160162
lastColonPos = -1;
161163
}
162164
}
163165

164-
if (socket != null && socket.Trim().Length > 0 && lastColonPos != -1)
166+
if (!string.IsNullOrWhiteSpace(socket) && lastColonPos != -1)
165167
{
166168
port = Convert.ToInt32(socket.Substring(lastColonPos + 1).Trim());
167169
}
@@ -176,7 +178,7 @@ public static int ParsePortFromSocket(string socket)
176178
/// <returns>true/false</returns>
177179
public static bool IsIPAddress(string socket)
178180
{
179-
if (socket == null || socket.Trim().Length == 0)
181+
if (string.IsNullOrWhiteSpace(socket))
180182
{
181183
return false;
182184
}
@@ -310,7 +312,7 @@ public static bool Parse(string endpointstring, out string host, out int port)
310312
}
311313
else
312314
{
313-
throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
315+
throw new FormatException($"Invalid endpoint ipaddress '{endpointstring}'");
314316
}
315317

316318
return rc;
@@ -327,7 +329,7 @@ public static IPEndPoint Parse(string endpointstring, int defaultport = -1)
327329
(defaultport < IPEndPoint.MinPort
328330
|| defaultport > IPEndPoint.MaxPort))
329331
{
330-
throw new ArgumentException(string.Format("Invalid default port '{0}'", defaultport));
332+
throw new ArgumentException($"Invalid default port '{defaultport}'");
331333
}
332334

333335
string[] values = endpointstring.Split(new char[] { ':' });
@@ -356,7 +358,7 @@ public static IPEndPoint Parse(string endpointstring, int defaultport = -1)
356358
}
357359
catch
358360
{
359-
throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
361+
throw new FormatException($"Invalid endpoint ipaddress '{endpointstring}'");
360362
}
361363
}
362364
}
@@ -377,7 +379,7 @@ public static IPEndPoint Parse(string endpointstring, int defaultport = -1)
377379
}
378380
else
379381
{
380-
throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
382+
throw new FormatException($"Invalid endpoint ipaddress '{endpointstring}'");
381383
}
382384

383385
if (port == -1)
@@ -396,7 +398,7 @@ private static int getPort(string p)
396398
|| port < IPEndPoint.MinPort
397399
|| port > IPEndPoint.MaxPort)
398400
{
399-
throw new FormatException(string.Format("Invalid end point port '{0}'", p));
401+
throw new FormatException($"Invalid end point port '{p}'");
400402
}
401403

402404
return port;
@@ -410,13 +412,13 @@ private static IPAddress getIPfromHost(string p)
410412

411413
if (hosts == null || hosts.Length == 0)
412414
{
413-
throw new ArgumentException(string.Format("Host not found: {0}", p));
415+
throw new ArgumentException($"Host not found: {p}");
414416
}
415417
return hosts[0];
416418
}
417419
catch
418420
{
419-
throw new ArgumentException(string.Format("Host not found: {0}", p));
421+
throw new ArgumentException($"Host not found: {p}");
420422
}
421423
}
422424

src/SIPSorcery/sys/TypeExtensions.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ public static class TypeExtensions
5555
/// </summary>
5656
public static bool IsNullOrBlank(this string s)
5757
{
58-
if (s == null || s.Trim(WhiteSpaceChars).Length == 0)
58+
if (s == null || s.AsSpan().Trim(WhiteSpaceChars).Length == 0)
5959
{
6060
return true;
6161
}
@@ -65,7 +65,7 @@ public static bool IsNullOrBlank(this string s)
6565

6666
public static bool NotNullOrBlank(this string s)
6767
{
68-
if (s == null || s.Trim(WhiteSpaceChars).Length == 0)
68+
if (s == null || s.AsSpan().Trim(WhiteSpaceChars).Length == 0)
6969
{
7070
return false;
7171
}
@@ -206,13 +206,11 @@ public static byte[] ParseHexStr(string hexStr)
206206
return buffer.ToArray();
207207
}
208208

209-
//#if NET472 || NETSTANDARD2_0
210209
public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value)
211210
{
212211
key = tuple.Key;
213212
value = tuple.Value;
214213
}
215-
//#endif
216214

217215
public static bool IsPrivate(this IPAddress address)
218216
{

0 commit comments

Comments
 (0)