So, I have a situation where I have to deal with huge (multidimensional) arrays and just wondered whether C# or C++ will perform better. (Note: I'm a beginner at C++, so don't expect too much knowledge about how it works!). I thought in terms of arrays both languages will perform similarly, maybe C++ could be slightly better BUT: The results tell other stories:
1012ms in C++ @32Bit
1020ms in C++ @32Bit
1002ms in C++ @32Bit
1155ms in C++ @64Bit
1098ms in C++ @64Bit
1122ms in C++ @64Bit
1136ms in C++ @64Bit
523ms in C# @32-Bit
545ms in C# @32-Bit
537ms in C# @32-Bit
536ms in C# @32-Bit
473ms in C# @64-Bit
501ms in C# @64-Bit
470ms in C# @64-Bit
498ms in C# @64-Bit
I performed one Test run at x86 and one at x64 architecture. Two things here: Why does C# do nearly two times better than C++? And why is C# actually faster in x64-Mode and C++ in x86-Mode?!? I really didn't expect that to happen.
As I told, I'm currently not that experienced in C++-Programming, but I tried my best reproducing my C#-Code in C++.
Here goes the code: C#
for (int j = 0; j < 4; j++)
{
Stopwatch sw = new Stopwatch();
sw.Start();
struct1[] s1 = new struct1[20000000];
int length = 20000000;
for (int i = 0; i < length; i++)
{
s1[i] = new struct1();
s1[i].samplechar = 'c';
s1[i].sampleInt = i * 2;
s1[i].sampledouble = Math.Sqrt(i);
}
sw.Stop();
GC.Collect();
Console.WriteLine(sw.ElapsedMilliseconds + "ms in C# @...-Bit");
}
AND struct1:
public struct struct1
{
public int sampleInt;
public double sampledouble;
public char samplechar;
}
C++:
for (int j = 0; j < 4; j++)
{
auto begin = std::chrono::high_resolution_clock::now();
struct1* s1 = new struct1[20000000];
int length = 20000000;
for (int i = 0; i < length; i++)
{
s1[i].sampleChar = 'c';
s1[i].sampleInt = i * 2;
s1[i].sampleDouble = sqrt(i);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << "ms in C++ @64Bit" << std::endl;
free(s1);
}
struct1:
struct struct1 {
public:
int sampleInt;
int sampleDouble;
char sampleChar;
};
Note: I did not include Garbage Collection/Free into performance measurement, since - in my case - there will be one huge array existing as long as the program is running. And I think it's clear that arrays of such sizes will be created/deleted too often unless you want to kill your machine...
Note2: Another confusing thing: While C++ consumes about 250MB of RAM, C# takes 500MB. But why?
Thanks in advance for any kind of explanation. Maybe I'm just getting this wrong and the failure just sat behind the display, but I'm although interested in why I get these results.
Edit: I'm running Visual Studio 2017RC on Windows 10. C++ Optimisation is disabled (/Od)