c# - Generic extension method is slower than non-generic extension method -
i wrote extension method lists finds index of given value (or next bigger value) in sorted list.
public static int linearsearch(this list<int> list, int startindex, int value) { (int = startindex; < list.count; i++) if (list[i].compareto(value) >= 0) return i; return -1; } public static int linearsearch<t>(this list<t> list, int startindex, t value) t : icomparable { (int = startindex; < list.count; i++) if (list[i].compareto(value) >= 0) return i; return -1; } as see wrote once generic once integers. if comment out int-specific version code runs approximately slower if prove both (given work on int-lists).
how can make generic version fast non-generic one? don't want copy , paste code performance ints , longs.
the test runs 10,000,000 random queries on sorted list of 1,000 integers.
linearsearch took 9823 ms // generic linearsearch took 1553 ms // int-specific test-code performance-measurements
class program { const int count = 1000; const int runs = 10_000_000; static list<int> list = new list<int>(); static list<int> queries = new list<int>(); static void main(string[] args) { measureruntime(createtestdata); measureruntime(linearsearch); } private static void linearsearch() { foreach (int query in queries) list.linearsearch(query); } private static void createtestdata() { random random = new random(0); list.add(0); (int = 0; < count; i++) list.add(list[list.count - 1] + random.next(0, 10)); (int = 0; < runs; i++) queries.add(random.next(0, list.count - 1)); } private static void measureruntime(action action) { stopwatch stopwatch = new stopwatch(); stopwatch.start(); action(); stopwatch.stop(); console.writeline($"{action.getmethodinfo().name} took {stopwatch.elapsedmilliseconds} ms"); } }
the problem used non-generic version icomparable instead of icomparable<t> caused performance-degregation. now, using icomparable<t> generic version runs fast type-specific one.
public static int linearsearch<t>(this list<t> list, int startindex, t value) t : icomparable<t> { (int = startindex; < list.count; i++) if (list[i].compareto(value) >= 0) return i; return -1; }
Comments
Post a Comment