Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of LINQ in simple operations

I have recently discovered LINQ and I find it very interesting to use. Currently I have the following function, and I am not sure whether it would be MORE efficient, and after all, produce the same output.

Can you please tell me your opinion about this?

The function simply removes punctuation in a very simple manner:

private static byte[] FilterText(byte[] arr)
    {
        List<byte> filteredBytes = new List<byte>();
        int j = 0; //index for filteredArray

        for (int i = 0; i < arr.Length; i++)
        {
            if ((arr[i] >= 65 && arr[i] <= 90) || (arr[i] >= 97 && arr[i] <= 122) || arr[i] == 10 || arr[i] == 13 || arr[i] == 32)
            {
                filteredBytes.Insert(j, arr[i]) ;
                j++;
            }
        }

        //return the filtered content of the buffer
        return filteredBytes.ToArray();
    }

The LINQ alternative:

    private static byte [] FilterText2(byte[] arr)
    {
        var x = from a in arr
                where ((a >= 65 && a <= 90) || (a >= 97 && a <= 122) || a == 10 || a == 13 || a == 32)
                select a;

        return x.ToArray();
    }
like image 733
test Avatar asked Nov 27 '22 22:11

test


1 Answers

LINQ usually is slightly less efficient than simple loops and procedural code, but the difference is typically small and the conciseness and ease of reading usually makes it worth converting simple projections and filtering to LINQ.

If the performance really matters, measure it and decide for yourself if the performance of the LINQ code is adequate.

like image 109
Mark Byers Avatar answered Dec 10 '22 12:12

Mark Byers