Most of programmers that began their career on the .NET framework have never asked themselves how the programs interact with the OS or computer through the framework.
Before I went over to .NET, I spended many hours trying to understand what makes the generated code so slow compared to other high level programming languages such as C/C++ or Delphi. I wrote several programs to compare native performance against .NET (C#) and discovered that, for relatively simple operations on integer and floating point types, native languages was over 300% faster than their .NET equivalent ones. The framework itself and the architecture behind is the cause of this. Every time you define a variable in a C program or a member in a C++ or Delphi class, the compiler allocates just as much memory as it needs to hold the variable value: 4 bytes for a 32-bit integer or pointer, 8 bytes for a 64-bit double floating point variable and so on.
While the Marshal.SizeOf method still tells us the truth about the size of an integer or a double type since the method gives the object's unmanaged size, there is a back side of this "truth". Once you've defined a member or variable of any type in .NET, the compiler must also allocate managed resources for, at least, the System.Object members. This means that you can invoke any of those members, for instance, int.ToString(). Easy and elegant but it has a price in form of a performance penalty.
Working on strings is not the best side of the .NET framework. Any time you copy or concatenate a string, the string class allocates a new string object that will be returned by the member in question. As the Copy method reveals, the returned string is allocated by the FastAllocateString call.
public static unsafe string Copy(string str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
int length = str.Length;
string str2 = FastAllocateString(length);
fixed (char* chRef = &str2.m_firstChar)
{
fixed (char* chRef2 = &str.m_firstChar)
{
wstrcpyPtrAligned(chRef, chRef2, length);
}
}
return str2;
}
In contrast, the C runtime library works on memory areas which is much faster but the programmer is responsible of keeping buffer sizes and boundaries.
It is well known that for large strings, the StringBuilder class, performs much better than the string class does. But this will not be covered here.
But, back to the question: Dot NET or dot Njet? For me the answer is definitly .NET as long as there are no high performance requirements. I suspect there is no programmer out there that would even consider writing a graphic-intensive game or a device driver in C#. For those purposes the Microsoft Visual Studio still gives you the C/C++ option and you have all combined in one development tool. If there comes a day when I must develop a time or resource critical application, I will dust off my C/C++ skills.
Cien años de una oportunidad (perdida)*
5 weeks ago

No comments:
Post a Comment