This post originated from an RSS feed registered with Agile Buzz
by Dave Churchville.
Original Post: Raw memory allocation speed - c++ vs c#
Feed Title: Agile Project Planning
Feed URL: http://feeds2.feedburner.com/AgileProjectPlanning
Feed Description: Thoughts on agile project planning, Extreme programming, and other software development topics
I've had several conversations on OO languages in the past couple of months. Going back to the migration from C to C++, developers became dependent on the 'new' operator and many times did so without understanding the consequences. In C++, 'new' = malloc() + non-inline function call (constructor).
So I started wondering - what are the performance differences between the C# and C++ new operators. To test this, I intentially created a small class that gets allocated over and over. To better compare the two languages since C# uses garbage collection, I intentially avoided the destructor call in C++. Since I cannot avoid the garbage collector, I decided that best case C# won't have time to call the gc and worst case C# will be penalized for it.
That said, I created the following code in C++. Keep in mind this is for the explicit purpose of isolating the function of allocating an object and calling a constructor.
C++ code
class OneInt
{
public:
int i;
public:
OneInt()
{
i=1;
}
};
int main(int argc, _TCHAR* argv[])
{
OneInt* oneInt = NULL;
for( int i = 0;i < 20000000; i++ )
oneInt = new OneInt();// intentional memory leak to avoid destructor call
return 0;
}
C# code
class OneInt
{
publicint i;
public OneInt()
{
i=1;
}
}
class Main
{
staticvoid Main(string[] args)
{
OneInt oneInt = null;
for( int i = 0;i < 20000000; i++ )
oneInt = new OneInt();
}
}
The results you ask? On a Pentium 4 3.2 ghz box...
C++ averaged slightly more than 5 seconds to run. C# averaged .15 seconds to run.
The +/- on both the C#/C++ code was less than .01 seconds, so I would consider that time to be TickCount resolution noise.
Having this type of code in a production environment is unrealistic - or at the very least, diplomas should be revoked. I'm not sure how much you can mark up to the organization of the constructor call IL, but I suspect the allocation of system memory in chunks larger than the requested object is playing into this. That task of preallocating memory and handling your own allocation pattern in C or C++ is very non-trivial work when the need arises.