Can anyone here tell me why
boolIsImageGreen(Image img); is computationally expensive than
boolIsImageGreen(Image *img); which was said by the MIT Notes faster.
Can anyone here tell me why
boolIsImageGreen(Image img); is computationally expensive than
boolIsImageGreen(Image *img); which was said by the MIT Notes faster.
Because a whole object contains more data then just a pointer to the object.
The first function requires that the Image object be copied when you make the call. The second function just makes a copy of the pointer which is inexpensive in comparison.
bit∙hub [bit-huhb] n. A source and destination for information.
A:
When you pass an large array of data as an argument to a function every single piece of data in that argument has to be copied from one place, to another. Then that function does it's thing to the data, and gives you back a bunch of data.
B:
A better function would be written to perform a process on data that already exists somewhere in memory, and doesn't need to copy ALL of the *already existing data from one place to another. You do that with pointers.
When you pass a pointer as an argument to a function, the only thing that is copied is a single value which represents a location in memory where a bunch of other data exists.
B is faster than A because A spends a lot of *extra time copying data *unnecessarily.
Note that this assumes that Image is expensive to copy (which for the sake of the example is probably a safe assumption).
If Image was just a single int, then it wouldn't be faster to pass a pointer. Also, if Image used some sort of shared_ptr style internal copying, then it probably wouldn't be that different either.