I even took a look at the decompiled code for Random and DateTime (using
Lutz Roeder's .NET Reflector).
Nothing in there that would hang onto objects. Random does create a seed
array of 56 elements - then its just a bunch of math and array operations to
determine next pseudo-random number.
Also, the empty constructor Random() calls Environment.TickCount internally
(which is Native code). I suspect this might be a bit faster and create
less garbage than you calling DateTime.Now.Millisecond as DateTime.Now
creates a new DateTime object whereas Environment.TickCount is static - so
only one object. Add that to Jon's comments and you should be able to get
the garbage creation done to zero!
Of course the garbage collector won't necessarily kick in unless you
generate a worthwhile amount of garbage (in its opinion).
If you get all the memory back when you call Collect yourself then I don't
think there's anything you can do about it.
Of course the other thing you can do is run your code in a memory profiler.
I personally can recommend SciTech
www.scitech.se/memprofiler - I've bought
it and used it to find several annoying memory consuming bugs in my code -
often in places you don't suspect as hanging onto objects - like updating a
GUI.
Hope this helps
Tom
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
James Sadlier <no*****@spam.me.no.spam> wrote:
<snip>
Any thoughts?
Apart from anything else, it's not a good idea to use Random like that.
Create one instance, and then use that everywhere. You might want to
use one instance per thread, admittedly - though I'd just put some
locking around each call.
Not sure why it should guzzle up memory though - I can't reproduce your
results on a small test basis. Do you have a short but complete program
which demonstrates the problem? See
http://www.pobox.com/~skeet/csharp/complete.html for what I mean.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too