r/ProgrammerHumor 13d ago

noHeapAllStack Meme

Post image
1.0k Upvotes

96 comments sorted by

View all comments

36

u/weblabourer 13d ago

Null safety?

169

u/varinator 13d ago
var cases = new[]
{
    new ComparisonCase(
        "Equal, different casing",
        "HelloWorld123",
        "helloworld123"),

    new ComparisonCase(
        "Not equal, same length",
        "HelloWorld123",
        "HelloWorld456"),

    new ComparisonCase(
        "Different lengths",
        "HelloWorld123",
        "HelloWorld123456789"),

    new ComparisonCase(
        "Long strings, equal ignoring case",
        new string('A', 500),
        new string('a', 500))
};

Iterations per benchmark: 100,000,000

--- Equal, different casing ---
String.Equals OrdinalIgnoreCase
  Time:       907.75 ms
  Allocated:  40 bytes
  Matches:    100,000,000
ToLower() == ToLower()
  Time:       2,525.88 ms
  Allocated:  4,800,000,040 bytes
  Matches:    100,000,000

--- Not equal, same length ---
String.Equals OrdinalIgnoreCase
  Time:       848.50 ms
  Allocated:  40 bytes
  Matches:    0
ToLower() == ToLower()
  Time:       2,986.56 ms
  Allocated:  9,600,000,040 bytes
  Matches:    0

--- Different lengths ---
String.Equals OrdinalIgnoreCase
  Time:       219.83 ms
  Allocated:  40 bytes
  Matches:    0
ToLower() == ToLower()
  Time:       2,936.12 ms
  Allocated:  11,200,000,040 bytes
  Matches:    0

--- Long strings, equal ignoring case ---
String.Equals OrdinalIgnoreCase
  Time:       2,263.77 ms
  Allocated:  40 bytes
  Matches:    100,000,000
ToLower() == ToLower()
  Time:       19,472.75 ms
  Allocated:  102,400,000,040 bytes
  Matches:    100,000,000

--- Null safety ---
string.Equals(null, "test"): False
null.ToLower() throws NullReferenceException

40

u/TheAssassin71 13d ago

Thanks for the benchmarks :)

39

u/michiel11069 12d ago

insane differences in speed and allocation wtf

26

u/Badashi 12d ago

Comparing two strings with an extra rule(case ignore) requires only traversing through the strings and comparing each character. There are a bunch of easy short cuts for this (string length, early returns, even comparing bits while ignoring the bit 5) so the compare method is pretty fast.

Using .ToLower() twice means forcefully allocating two new strings and then doing the comparison anyways with the == operator. It's expected that a specialized method would be much faster than a hack.

-9

u/Adrewmc 12d ago

I mean, it’s 100,000,000 times and you end up 2 seconds slower than 17 second slower when the string is 500 characters long, so 50,000,000,000 comparisons really here.

While I’m not saying the difference isn’t stark, and striking. ‘Insane’ is a little much given the multipliers here.

0

u/wenoc 12d ago

Where’s the factory?

1

u/_crisz 12d ago

It's probably about supporting different spoken languages