May the gods spare us from “clever” programmers.

Esben found this little block of C# code:

System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
long check = proc.PrivateMemorySize64;
if (check > 1150000000)
{
   MessageBox.Show(Strings.ReportForm_HighMemoryUse);
   return;
}

Even before you check on the objects and methods in use, it’s hard to figure out what the heck this method is supposed to do. If some memory stat is over a certain size, pop up a message box and break out of the method? Why? Isn’t this more the case for an exception? Since the base value is hard coded, what happens if I run this code on a machine with way more RAM? Or configure the CLR to give my process more memory? Or…

If the goal was to prevent an operation from starting if there wasn’t enough free memory, this code is dumb. It’s “clever”, in the sense that the original developer said, “Hey, I’m about to do something memory intensive, let me make sure there’s enough memory” and then patted themselves on the head for practicing defensive programming techniques.

But that isn’t what this code exactly does. PrivateMemorySize simply reports how much memory is allocated to the process. Not how much is free, not how much is used, just… how much there is. That number may grow, as the process allocates objects, so if it’s too large relative to available memory… you’ll be paging a bunch, which isn’t great I suppose, but it still doesn’t explain this check.

This is almost certainly means this was a case of “works on my/one machine”, where the developer tuned the number 1550000000 based on one specific machine. Either that, or there was a memory leak in the code- and yes, even garbage collected languages can still have memory leaks if you’re an agressively “clever” programmer- and this was the developer’s way of telling people “Hey, restart the program.”

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!