扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
i4o是对LINQ的一个扩展,通过允许我们在对象上添加“索引”来提高LINQ运算速度,作者号称使用i4o后速度提升often over one thousand times。
我们在进行数据库查询优化时,往往第一想到的就是给Tables添加合适的Index来大幅度提升执行效率,i4o的实现也是类似这个方式,我们只要给class添加一个Indexable属性,然后使用IndexableCollection<T>来实现一个使用“索引”的类的集合就可以了,这样比起顺序性的搜索就在一定程度上提高了速度。
比如我们可以这样用:

var customers = new IndexableCollection<CnblogUser>()
{ 
new Customer
{Key = 1, Name = "fanweixiao" },
new Customer
{Key = 2, Name = "lovewangshu" }
};
//extend the where when we are working with indexable collections!
public static IEnumerable<T> Where<T>
(
this IndexableCollection<T> sourceCollection,
Expression<Func<T, bool>> expr
)
{
//our indexes work from the hash values of that which is indexed, regardless of type
int? hashRight = null;
bool noIndex = true;
//indexes only work on equality expressions here
if (expr.Body.NodeType == ExpressionType.Equal)
{
//Equality is a binary expression
BinaryExpression binExp = (BinaryExpression)expr.Body;
//Get some aliases for either side
Expression leftSide = binExp.Left;
Expression rightSide = binExp.Right;
hashRight = GetHashRight(leftSide, rightSide);
//if we were able to create a hash from the right side (likely)
if (hashRight.HasValue && HasIndexablePropertyOnLeft<T>(leftSide,sourceCollection))
{
//cast to MemberExpression - it allows us to get the property
MemberExpression propExp = (MemberExpression)leftSide;
string property = propExp.Member.Name;
Dictionary<int, List<T>> myIndex =
sourceCollection.GetIndexByProperty(property);
if (myIndex.ContainsKey(hashRight.Value))
{
IEnumerable<T> sourceEnum = myIndex[hashRight.Value].AsEnumerable<T>();
IEnumerable<T> result = sourceEnum.Where<T>(expr.Compile());
foreach (T item in result)
yield return item;
}
noIndex = false; //we found an index, whether it had values or not is another matter
}
}
if (noIndex) //no index? just do it the normal slow way then

{
IEnumerable<T> sourceEnum = sourceCollection.AsEnumerable<T>();
IEnumerable<T> result = sourceEnum.Where<T>(expr.Compile());
foreach (T resultItem in result)
yield return resultItem;
}
}
而SLINQ则是可以让LINQ作用于streaming data上的,目前这个项目只算是个Demo版本,实现方式是为LINQ添加了一系列的扩展方法,有兴趣的朋友可以down下sourcecode来看看,需要注意的是要安装Visual Studio Orcas beta 1。
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。