Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use functions like CGRectMake?

I'm curious why functions like CGRectMake and CGPointMake exist and are widely used. when, instead, you can do:

(CGRect){{x, y}, {width, height}}

surely this is more efficient (though I'm guessing not by much) as there is no function call?

Also you can set the origin and size like:

 (CGRect){origin, size}

and as a mixture:

 (CGRect){origin, {width, height}}

What is the reason for not using this, and preferring the Make functions?

like image 715
Jonathan. Avatar asked Jul 28 '12 11:07

Jonathan.


1 Answers

It isn't more efficient, actually. The CGRectMake function (and others) are declared as static inline, which means the compiler copy pastes the function code straight into every place it's used:

CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)

where

#  define CG_INLINE static inline

You go from

// code
CGRect myRect = CGRectMake(1,2,3,4);
// code

to

// code
CGRect myRect;
myRect.origin.x = 1; myRect.origin.y = 2;
myRect.size.width = 3; myRect.size.height = 4;

which in principle is no different from

CGRect myRect = (CGRect){1,2,3,4};

after compiler optimizations and such.

As said above you add a dependency on CGRect being a struct of 4 numbers aligned a certain way as opposed to using a function that has more guarantee to it.

like image 81
Kalle Avatar answered Oct 28 '22 01:10

Kalle