четверг, 4 октября 2012 г.

String.Join vs Linq.Aggregate

Let's say we have collection of some objects like:

class Product
{
       int ProductNumber;
       string ProductName;
}

We get list of these classes rom database using LinqToEntity:

List<Product> prop = context.Product.Where(P => P.PropertyNumber == 1).ToList();

Now we want to get comma delimited string of ProductNumbers.

We have two ways: use linq aggregate or use string.Join;
I wanted to check what is faster and wrote some code:


List<Product> prop = context.Product.ToList();

long start = DateTime.Now.Ticks;
prop.Aggregate("", (total, next) => total + "," + next.ProductNumber).TrimStart(',');
Console.WriteLine(new TimeSpan(DateTime.Now.Ticks - start));

start = DateTime.Now.Ticks;
List<int> propint = prop.Select(P => P.ProductNumber).ToList();
string.Join(",", propint);
Console.WriteLine(new TimeSpan(DateTime.Now.Ticks - start));



Aggregate:
00:00:25.9222917

String.Join:
00:00:00.0500064

In my example there were 16972 of products in database. So even if we use additional linq to select only one field from base collection string.Join works much faster.

after that I found another code with Linq.Aggregate:


start = DateTime.Now.Ticks;
prop.Aggregate(new StringBuilder(), (total, next) => total.Append(",").Append(next.ProductNumber)).ToString().TrimStart(',');
Console.WriteLine(new TimeSpan(DateTime.Now.Ticks - start));

This code gave me exactly same results as String.Join();

So finally I think String.Join() uses same algorithm as aggregate, but simple uses string builder to use memory more effective.