none
Performance issues with Class members RRS feed

  • Question

  • Hi,

    I have created a class called MyData which has around 30 public properties. Now I am creating 500000 instances of this class and adding them to an ObservableCollection. This process is taking around 1.5 secs. But if I remove those properties from class and then create those number of instances, it is taking no time.

    MyCode:

     ObservableCollection<MyData> data = new ObservableCollection<MyData>();

                for (Int32 i = 0; i < 500000; i++)
                {
                    MyData dt = new MyData();
                    data.Add(dt);
                }

    Here MyData is a class with 30 public properties.

    Can anybody please tell me why it is taking lot of time to create those number of instances?



    • Edited by JordanSmith Thursday, June 21, 2012 9:44 AM
    Thursday, June 21, 2012 9:42 AM

Answers

  • The "Add" method is performing a deep copy of the elements of "dt" into data's ( ObservalbleCollection ) memory and thats where the time is consumed.
    Thursday, June 21, 2012 1:22 PM
  • 30 properties. Even if each property is of type Byte, then it's 30 bytes per instance. for 500000 instances, it's 15000000 bytes. So, CLR has to deal with some sufficently large memory which involves numerous garbage collections. Hence, it definitely takes some time.

    On the other hand, if the class doesn't have any property (I assume empty class), then CLR has to deal with very little memory and very few or no garbage collections. Hence, it results in faster execution.

    I hope this makes sense.


    Please mark this post as answer if it solved your problem. Happy Programming!

    Thursday, June 21, 2012 4:32 PM

All replies

  • The "Add" method is performing a deep copy of the elements of "dt" into data's ( ObservalbleCollection ) memory and thats where the time is consumed.
    Thursday, June 21, 2012 1:22 PM
  • 30 properties. Even if each property is of type Byte, then it's 30 bytes per instance. for 500000 instances, it's 15000000 bytes. So, CLR has to deal with some sufficently large memory which involves numerous garbage collections. Hence, it definitely takes some time.

    On the other hand, if the class doesn't have any property (I assume empty class), then CLR has to deal with very little memory and very few or no garbage collections. Hence, it results in faster execution.

    I hope this makes sense.


    Please mark this post as answer if it solved your problem. Happy Programming!

    Thursday, June 21, 2012 4:32 PM