Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq group by property performance

On a parametrizable query inspired by this post LINQ group by property as a parameter I've obtained a nice parametrizable query, but with one drawback on performances.

 public static void GetExpensesBy<TKey>( Func<Obj, TKey> myGroupingProperty)
    {
        var query = (from item in dataset
                     orderby item.ExpenseTime descending
                     select item).GroupBy(myGroupingProperty);
        // ....
    }
    // ..
    GetExpensesBy(p=> p.Column)

is much slower than the direct query

 var query = (from item in expense
                     orderby item.ExpenseTime descending
                     select item).GroupBy(p => p.Column);

The difference is about 2s vs 0.1s in a table of 13000 rows.

Would you have any idea how to improve the first syntax to improve the performance?

like image 205
Antoine Dussarps Avatar asked Mar 13 '23 17:03

Antoine Dussarps


1 Answers

Change your parameter type for an Expression:

public static void GetExpensesBy<TKey>( Expression<Func<Obj, TKey>> myGroupingProperty)
{
 //...
}

Passing a Func<T> you are calling GroupBy from IEnumerable<T>

like image 184
octavioccl Avatar answered Mar 20 '23 18:03

octavioccl