I have been learning to program and I chose C++ and C# programming as first languages. More specifically, I have an old C book someone was kind enough to let me borrow and I'm using it to learn C#. I use Visual Studio Express and write in C++ and C#. One area that interests me is the ability to do direct memory management. I am trying to learn to use this to optimize my code. However, I am struggling to do it properly and actually see any real performance improvement. For example, here is the following code in C#:
unsafe static void Main(string[] args)
{
int size = 300000;
char[] numbers = new char[size];
for (int i = 0; i < size; i++)
{
numbers[i] = '7';
}
DateTime start = DateTime.Now;
fixed (char* c = &numbers[0])
{
for (int i = 0; i < 10000000; i++)
{
int number = myFunction(c, 100000);
}
}
/*char[] c = numbers; // commented out C# non-pointer version same
speed as C# pointer version
{
for (int i = 0; i < 10000000; i++)
{
int number = myFunction(c, 100000);
}
}*/
TimeSpan timeSpan = DateTime.Now - start;
Console.WriteLine(timeSpan.TotalMilliseconds.ToString());
Console.ReadLine();
}
static int myFunction(ref char[] numbers, int size)
{
return size * 100;
}
static int myFunction(char[] numbers, int size)
{
return size * 100;
}
unsafe static int myFunction(char* numbers, int size)
{
return size * 100;
}
No matter which of three methods I call, I am getting the same execution speed. I'm also still trying to wrap my head around the difference between using ref and using a pointer, except that's probably something that will take time and practice.
What I don't understand, however, is that I am able to produce a very significant performance difference in C++. Here is what I came up with when I attempted to approximate the same code in C++:
/*int myFunction(std::string* numbers, int size) // C++ pointer version commented
out is much faster than C++ non-pointer version
{
return size * 100;
}*/
int myFunction(std::string numbers, int size) // value version
{
return size * 100;
}
int _tmain(int argc, _TCHAR* argv[])
{
int size = 100000;
std::string numbers = "";
for (int i = 0; i < size; i++)
{
numbers += "777";
}
clock_t start = clock();
for (int i = 0; i < 10000; i++)
{
int number = myFunction(numbers, 100000);
}
clock_t timeSpan = clock() - start;
std::cout << timeSpan;
char c;
std::cin >> c;
return 0;
}
Can anyone tell me why my C# code isn't benefitting from my use of references or pointers? I've been reading stuff online and whatnot, except I'm stuck.
/*and*/to comment everything between them instead of having to use//on every line.