Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits (and drawbacks) of C# nested method calls

Tags:

methods

c#

nested

I'm getting back into coding in C#, after being neck deep in Objective-C. And I was wondering, in C# are there any particular benefits or drawbacks to writing your code with nested method calls, in terms of performance, memory overhead, and code readability & maintenance? Or is it better to go with easier to read and/or easier to follow code, over any possible speed or memory benefits (the memory benefits part can be the ObjC/non-managed code talking)?

Example (x, y, z, w, t, e & g are all int's):

// non-nested
// someMethod returns an int

int b = someMethod(w,t,e);
int a = ((x + y) * b);
int c = a + (b * g);
return a + b + c;


// nested
// someMethod returns an int
return (((x + y) * someMethod(w,t,e)))
+ (someMethod(w,t,e)) + (((x + y) * someMethod(w,t,e))
+ (someMethod(w,t,e) * g));

It's easier to follow the non-nested code, but in the nested code you're not having to instantiate the three variables; it's also four lines of code to one line of code (albeit the one line is broken up into three lines for the sake of readability). I'm just not sure which way is better, or more accepted within the C# programming community. Any insight would be much appreciated. Thanks!

like image 526
RabbitEar Avatar asked Dec 03 '25 02:12

RabbitEar


1 Answers

If someMethod(w,t,e) does something non-trivial, calling it three times will be slower than making a single call and storing the result.

Note that the two expressions are equivalent only if the function someMethod(w,t,e) is a "pure" function, meaning that it is free of side effects, and that it returns the same value for the same set of arguments.

During the initial design and coding you should strive for the best readability. Considering the overhead of method calls before profiling is a premature optimization.

like image 75
Sergey Kalinichenko Avatar answered Dec 04 '25 16:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!