Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure memory usage of a code?

Tags:

c#

.net

memory

I'm trying to measure memory usage of a code, but i don't know how to proceed. I don't want to use "DotMemory" or any "profiler" i need to do it by programming.

There is any way to know how much object was allocated ? Like 5 int(4 bytes) + 4 Object (16 bytes) ...

I used

process.WorkingSet64

but every time I run the same code I get different values.

So what is the best way to measure memory usage of a code ?

like image 911
omega Avatar asked Dec 30 '25 22:12

omega


1 Answers

.NET is a managed memory environment. This means that allocation and deallocation is handled transparently for you, but it also means that the memory usage patterns aren't entirely deterministic.

99.9% of the time, this isn't an issue at all. The rest of the time, you should focus your work on the area that matters - usually, it's pretty easy to handle all the critical load in one place.

Your question suggests you come from a C/Pascal background - the tradeoff of managed memory is that you shoudln't really care about memory - sure, you want to pay attention not to outright waste memory, but taking twice as much memory as strictly necessary usually isn't a thing to lose sleep about. "Memory before" and "memory after" is a question that really doesn't make much sense in a multi-threaded environment - your method isn't the only one that's running in the meantime.

like image 120
Luaan Avatar answered Jan 01 '26 13:01

Luaan