Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reduce memory allocation by passing DateTime parameter by reference in c#?

In C#, is there any significant reduction in memory allocation when passing a DateTime reference as a parameter to a function as opposed to passing it by value?

int GetDayNumber(ref DateTime date)

vs

int GetDayNumber(DateTime date)

The code inside the function is not modifying the date in any case.

like image 397
jeroko Avatar asked Feb 17 '12 11:02

jeroko


2 Answers

A DateTime is a 8 byte struct. A ref has 4 or 8 bytes depending on your target architecture. So at best you'd save 4 bytes of stack memory, which is completely irrelevant.

It's even likely that ref prevents some optimizations, such as placing the DateTime in a register, thus actually increasing memory use.

This is a clear case of premature optimization. Don't do this.

like image 151
CodesInChaos Avatar answered Oct 20 '22 08:10

CodesInChaos


As with any other similar question you need to time it yourself. Would a few processor ticks play significant role? Would a few extra bytes play major part in memory consumption in your application?

Leave the micro optimisation and concentrate on real problem solving first.

like image 2
oleksii Avatar answered Oct 20 '22 10:10

oleksii