Tuesday, 15 February 2011

c# - Optimizing an IEnumerable extension MaxBy -



c# - Optimizing an IEnumerable extension MaxBy -

i have ienumerable extension maxby used like

var longest = new [] {"cat", "dogs", "nit" }.maxby(x=>x.count())

should be

"dogs"

with implementation*emphasized text*

public static t maxby<t,m>(this ienumerable<t> this, func<t,m> selector) m : icomparable { homecoming .skip(1) .aggregate ( new {t=this.first(), m = selector(this.first())} , (a, t) => { var m = selector(t); if ( m.compareto(a.m) > 0) { homecoming new { t, m }; } else { homecoming a; } } , => a.t); }

it's quite elegant , purely functional see problem. i'm using anonymous objects reference types , require garbage collection. in worst case when travesing ienumerable of length n create n memory allocations , n objects need garbage collection.

i write code utilize external mutable accumulator aesthetically i'd prefer stick pattern have.

however concerns in reality problem? .net generational garbage collector identify these objects short lived, 1 @ time , optimize away happening? or improve create custom value type ( struct ) hold accumulator instead of using anonymous object.

** edit **

this non functional way it.

public static t maxby<t,m>(this ienumerable<t> this, func<t,m> selector) m : icomparable { var t = this.first(); var max = selector(t); foreach (var item in this.skip(1)) { var m = selector(item); if ( m.compareto(max) > 0) { max = m; t = item; } } homecoming t; }

c# .net garbage-collection ienumerable maxby

No comments:

Post a Comment