Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to make your program use less memory

Software will use memory, no big suprise, but how do you keep this usage to a minimum in comparison to how big your program is.

Best example I think would be Firefox. Some users have experienced it, others haven't, but it's pretty safe to say that all the previous versions of Firefox used much more memory then the current version. Yet still, functionality expands and options are added. I'd expect the memory usage to go up as extra options and such stuff gets added.

So in other words, there must be methods by which to make sure your program doesn't use up the memory of the computer.

So, I'm turning this into a "best-practices" question, asking all of you what your little tricks and tweaks are to make your program do what it does, with less CPU then you'd normally think. And also, what to most certainly avoid.

A little side-question here: I came accross something in a book about C#. Apparently, when coding an Enum, it's possible to set the size of the index of this Enum. With large Enum's, you should let the compiler handle it I guess, but for an Enum which only holds like 2 or 3 items, you can do this:

public enum HTMLTYPE : sbyte
{
    HTML401,XHTML10,XHTML11
}

For those of you who don't know why, apparently the amount of memory reserved for the index of any Enum is automatically set to an integer in C#. So in other words, that amount of memory is going to be reserved. But when defining so little things in your Enum, an integer is a waste of space. The book claimed that this could cut down the amount of memory used by the program. I'm wondering if this is true.

EDIT: indeed, it should be memory, darn me. Changed all entries.

like image 364
Vordreller Avatar asked Oct 22 '25 12:10

Vordreller


1 Answers

First, you're probably confusing CPU and RAM (aka memory). CPU is the processor, i.e., what runs your code against your data. Memory is where that code and data are stored.

That enum trick should actually be avoided. First, sbyte isn't CLS-compliant. Then it can limit future expansion. There's always the fact that the CPU always uses entire words (int in 32-bit architectures and long in 64-bit architectures). You lose all that, and for what gains? A few bytes off your memory footprint.

More to the point, follow these wise words: Premature optimization is the root of all evil.

That means, only optimize when it is really required. Measure things first. You'll quite likely realize it's not those three bytes from the enum that need cutting back.

like image 76
R. Martinho Fernandes Avatar answered Oct 24 '25 20:10

R. Martinho Fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!