yaapelsinko
yaapelsinko

Reputation: 689

How to optimize lambda at runtime?

I've got a test job to optimize lambda-expression at runtime. Assuming the lambda contains some "heavy" function calls, what I need is to change the lambda so that all that function calls were cached into temporary variables, which then can substitute the actual function calls in the lambda body.

It must be a function that gets a lambda as a parameter, and returns optimized lambda which you can call then.

I wonder what section of C# is this at all? I mean, like, "learn about reflections" or "learn about generics". What do I need to learn in this case?

Upvotes: 2

Views: 376

Answers (2)

Dtex
Dtex

Reputation: 2623

I think Memoization is the technique you are looking for.

Here is an article that explains how you can achieve memoization in c# using generics and lambda expression.

Finally, you can find an actual implementation of the technique in ReactiveUI MemoizingMRUCache.

Upvotes: 0

xanatos
xanatos

Reputation: 111870

Unless your heavy function calls are deterministic, and you can prove that they are always called with the same parameters, you can't do it.

For example, in C#

var lst = new List<string> { "Foo", "Bar" };

bool r1 = lst.Remove("Foo"); // true, and has modified lst
bool r2 = lst.Remove("Foo"); // false, and hasn't modified lst

bool r3 = lst.Remove("Bar"); // true, and has modified lst, note different parameter
bool r4 = lst.Remove("Baz"); // false, and hasn't modified lst, note different parameter

How can you detect if Remove is deterministic or not? You can't (technically you could disassemble it and check it, but it is very difficult)... And then how could you detect if it is being called with the same parameters? This is doable, but quite difficult.

Now... as a test job... I see three possibilities:

  • it is a false test, where you must comprehend this and report it
  • you didn't comprehend the test job
  • you didn't give us some important informations (for example that you have to replace some specific method calls that don't have parameters and are static or something similar, and that are guaranteed to be deterministic)

Upvotes: 1

Related Questions