Ottimizzare con C# non è come con C++
Ogni tanto si scoprono cose interessanti. Cercando di ottimizzare una funzione, mi sono imbattuto in un dubbio che vi sottopongo: secondo voi (senza eseguire il codice) è più veloce il codice di CompareU o di CompareU2?
Se qualcuno è interessato a rispondere alla domanda, sarà interessante discutere privatamente sul perché quello più veloce sia più veloce... :-)
static bool CompareU(string match, string compared)
{
if (match.Length != compared.Length) return false;
unsafe
{
fixed( char* _m1 = match, _m2 = compared )
{
char* m1 = _m1;
char* m2 = _m2;
for (int i = 0; i < match.Length; i++)
{
char ch = *m1++;
if (ch != '?')
{
if (*m2 != ch) return false;
}
m2++;
}
}
}
return true;
}
static bool CompareU2(string match, string compared)
{
if (match.Length != compared.Length) return false;
unsafe
{
fixed (char* m1 = match, m2 = compared)
{
for (int i = 0; i < match.Length; i++)
{
char ch = m1[i];
if (ch != '?')
{
if (m2[i] != ch) return false;
}
}
}
}
return true;
}