February 16, 2011

Measuring memory cunsumption

When using any object oriented programming language you sooner or later start using your own objects. But when creating your own class - more complex class that uses a lot of other objects, it may be a good idea to know how much memory your object cunsumes - You may want to maintain thousands of your objects in some collection for some time and it costs some memory..

A good way to get to know how much memory your object eats is using GetTotalMemory() method in System.GC.

long memoryStart = System.GC.GetTotalMemory(true);

// Generate some of your objects
ICollection<myobject> myObjects = List<myobject>();
for (int i = 0; i < 10000; i++)
  myObjects.Add(new MyObject);

long memoryEnd = System.GC.GetTotalMemory(true);

MessageBox.Show((memoryEnd - memoryStart).ToString());

That gives you how much memory consume 10 000 objects of your class. Divide it by 10 000 and it's the memory consumption of one object.

February 14, 2011

Time measurement with Stopwatch

When I need to measure how long some action take I use Stopwatch class. It's in System.Diagnostics.
Here's sample:

Stopwatch stopwatch = new Stopwatch();

// action I want to measure


Or just

Stopwatch stopwatch = Stopwatch.StartNew();

// action I want to measure


It's more precise than using DateTime.

February 11, 2011

Web tip - WPFwiki

A few days ago I found an interrresting source of answers to some WPF questions. It's called WPFwiki and can be found here www.wpfwiki.com.
The good thing is that the content is being updated time to time, so there might be a lot of interresting information.

January 11, 2011

Converting/parsing string to int

Common C# application uses TextBoxes to enter some values which the program works with. So there is a need to convert some string from raw input to some other type. These examples show how to convert string to int.

Using static class Convert:
string input = "10";

int number;

number = Convert.ToInt32(input);

This method (and similar for other value types) can throw FormatException when input is not in the correct format (is not a number) of OverflowException if the string input is number but it's value is less than MinValue or greater than MaxValue.

The second option is to use Parse method:
result = int.Parse(input);

But this method can also throw some exceptions. Two of them are mentioned before: FormatException and OverflowException. Another exception, ArgumentNullException, is thrown when the argument (string input) is null.

The third option and in my opinion the best solution is to use TryParse method. This method doesn't throw exceptions so the isn't any exception handling slowing down the application. It only return true if the parse succeeded or false if it didn't.
bool parsed;
parsed = int.TryParse(input, out result);

I hope someone may find this snippet useful.