DEV Community

Szymon Hałucha
Szymon Hałucha

Posted on

Fast string case transformation for the C#

Recently, I needed for my source generator a simple package that converts names from PascalCase to camelCase and vice versa. The available packages were not very optimal in terms of allocated memory, so I wrote my own, here are examples of usage along with a performance comparison.

GitHub: https://github.com/SzymonHalucha/Minerals.StringCases
NugGet: https://www.nuget.org/packages/Minerals.StringCases/

using Minerals.StringCases;

string sampleText = "  _ example Variable - - Name   321";

string pascalCase = sampleText.ToPascalCase();
// ExampleVariableName321

string camelCase = sampleText.ToCamelCase();
// exampleVariableName321

string underscoreCamelCase = sampleText.ToUnderscoreCamelCase();
// _exampleVariableName321

string kebabCase = sampleText.ToKebabCase();
// example-variable-name-321

string snakeCase = sampleText.ToSnakeCase();
// example_variable_name_321

string macroCase = sampleText.ToMacroCase();
// EXAMPLE_VARIABLE_NAME_321

string trainCase = sampleText.ToTrainCase();
// Example-Variable-Name-321

string titleCase = sampleText.ToTitleCase();
// Example Variable Name 321
Enter fullscreen mode Exit fullscreen mode

Here is a comparison of the speed and amount of memory allocation with the most popular NuGet package similar to Minerals.StringCases version 0.1.0 - CaseExtesions version 1.1.0.

String used to perform the comparison:

string sampleText = "  _ example Variable - - Name   321";
Enter fullscreen mode Exit fullscreen mode

Results

BenchmarkDotNet v0.13.12, Windows 10 (10.0.19045.4291/22H2/2022Update)
AMD Ryzen 5 2600, 1 CPU, 12 logical and 6 physical cores
.NET SDK 8.0.204
  [Host]     : .NET 8.0.4 (8.0.424.16909), X64 RyuJIT AVX2
  Job-LXTTHC : .NET 8.0.4 (8.0.424.16909), X64 RyuJIT AVX2
Enter fullscreen mode Exit fullscreen mode
Method Mean Error StdDev Gen0 Allocated
CamelCase_Minerals_StringCases 153.0 ns 1.32 ns 1.03 ns 0.0343 144 B
PascalCase_Minerals_StringCases 159.2 ns 2.11 ns 1.98 ns 0.0343 144 B
SnakeCase_Minerals_StringCases 187.9 ns 1.12 ns 1.00 ns 0.0362 152 B
KebabCase_Minerals_StringCases 202.1 ns 1.94 ns 1.82 ns 0.0362 152 B
TrainCase_Minerals_StringCases 213.2 ns 1.22 ns 1.08 ns 0.0362 152 B
- - - - - -
PascalCase_CaseExtensions 517.7 ns 4.23 ns 3.96 ns 0.0973 408 B
KebabCase_CaseExtensions 529.3 ns 3.52 ns 3.29 ns 0.0992 416 B
SnakeCase_CaseExtensions 531.2 ns 4.56 ns 4.26 ns 0.0992 416 B
TrainCase_CaseExtensions 533.5 ns 5.08 ns 4.50 ns 0.0992 416 B
CamelCase_CaseExtensions 549.7 ns 6.09 ns 5.69 ns 0.0973 408 B

Top comments (0)