performance - ANSI C #define VS functions -
i have question performance of code. let's have struct in c point:
typedef struct _cpoint { float x, y; } cpoint;
and function use struct.
float distance(cpoint p1, cpoint p2) { return sqrt(pow((p2.x-p1.x),2)+pow((p2.y-p1.y),2)); }
i wondering if smart idea replace function #define,
#define distance(p1, p2)(sqrt(pow((p2.x-p1.x),2)+pow((p2.y-p1.y),2)));
i think faster because there no function overhead, , i'm wondering if should use approach other functions in program increase performance. question is:
should replace functions #define increase performance of code?
no. should never make decision between macro , function based on perceived performance difference. should evaluate soley based on merits of functions on macros. in general choose functions.
macros have lot of hidden downsides can bite you. case in point, translation macro here incorrect (or @ least not semantics preserving original function). argument macro distance
gets evaluated 2 times each. imagine made following call
distance(getpointa(), getpointb());
in macro version results in 4 function calls because each argument evaluated twice. had distance
been left function result in 3 function calls (distance , each argument). note: i'm ignoring impact of sqrt
, pow
in above calculations they're same in both versions.
Comments
Post a Comment