Efficient Cartesian Product algorithm

后端 未结 6 1673
太阳男子
太阳男子 2020-11-29 07:00

Can somebody please demonstrate for me a more efficient Cartesian product algorithm than the one I am using currently (assuming there is one). I\'ve looked around SO and go

6条回答
  •  清酒与你
    2020-11-29 07:41

    You can't really change the performance of a nested loop without some additional knowledge, but that would be use-specific. If you have got n items in is and m items in js, it is always going to be O(n*m).

    You can change the look of it though:

    var qry = from i in is
              from j in js
              select /*something involving i/j */;
    

    This is still O(n*m), but has nominal extra overhead of LINQ (you won't notice it in normal usage, though).

    What are you doing in your case? There may be tricks...

    One thing to definitely avoid is anything that forces a cross-join to buffer - the foreach approach is fine and doesn't buffer - but if you add each item to a List<>, then beware the memory implications. Ditto OrderBy etc (if used inappropriately).

提交回复
热议问题