vendredi 3 juillet 2020

Inlining a method to increase performance but it executes slower in C#

I am trying to remove a method to optimize my code. It seems I didn't gain any performance, moreover, the "optimized" code is slower! Is it faster to call a method than to create a variable in the loop? Why?

Why the following code is faster (1.3 seconds)

public void getPureText(string notClearedText)
{
    string peeledText = "";


    foreach (var symbol in notClearedText)
    {
        if(isCyrillic(symbol))
            peeledText += Char.ToLower(symbol);
        else
            peeledText += " ";
    }
}

private bool isCyrillic(int letterCode)
{
    switch (letterCode)
    {
        case 1028: // Є
        case 1108: // є
        case 1030: // І
        case 1110: // і
        case 1031: // Ї
        case 1111: // ї
        case 1168: // Ґ
        case 1169: // ґ
        case 32:  // " "
        case 39:  // '
                  //case 45:  // -
            return true;
        default:
            return
                1040 <= letterCode && letterCode <= 1103 &&  // Cyrillic
                letterCode != 1066 &&  // Ъ
                letterCode != 1067 &&  // Ы
                letterCode != 1098  // ъ
                ||
                65 <= letterCode && letterCode <= 90
                ||
                97 <= letterCode && letterCode <= 122
                ;
    }

}

than the "optimized" version (1.6 seconds)? What am I missing?

public void getPureText(string notClearedText)
{
    string peeledText = "";

    foreach (var symbol in notClearedText)
    {
      int letterCode = symbol;

      switch (letterCode)
      {
        case 1028: // Є
        case 1108: // є
        case 1030: // І
        case 1110: // і
        case 1031: // Ї
        case 1111: // ї
        case 1168: // Ґ
        case 1169: // ґ
        case 32:  // " "
        case 39:  // ' //case 45:  // -
            peeledText += Char.ToLower(symbol);
            break;
        default:
            if (
                1040 <= letterCode && letterCode <= 1103 && // Cyrillic
                letterCode != 1066 && // Ъ
                letterCode != 1067 && // Ы
                letterCode != 1098 // ъ
                ||
                65 <= letterCode && letterCode <= 90
                ||
                97 <= letterCode && letterCode <= 122
            )
                peeledText += Char.ToLower(symbol);
            else
                peeledText += " ";
            
            break;
         }
    }
}

I have run dozens of tests using

void TestPerformance()
{
    Stopwatch sw = new Stopwatch();

    sw.Start();
    _textRepository.getPureText(RawTextExamples.veryLongText);
    sw.Stop();

    unitTestFormGuess.show(sw.Elapsed.ToString());
}

P.S. As you see I removed some code from getPureText(), made it return void, then measured time again: the same result. Something wrong is there...

P.P.S. Configuration: Debug.

Aucun commentaire:

Enregistrer un commentaire