Function pointer and normal function - function-pointers

What are the differences between normal function and function pointer.
One which I know is in case you are using a library in your software stack which
gives you only function pointers then you can fill in the pointers for
use later.

Calling a function through a function pointer means the call cannot be inlined; in certain cases, this can result in quite a performance penalty. (For example, C's qsort() going through a function pointer for each compare, vs. C++'s sort() being able to inline the comparison.)
Declaring a function pointer requires a non-trivial syntax that is not as commonly used as other parts of the language, resulting in a "mental speed-bump" for most when reading the source. It is usually typedef'ed for that reason.

A function pointer is just a pointer to a normal function. It can be passed around like any other pointer, and can be invoked somewhere other than where it was created.

Related

Effect of Anonymous function in performance in Dart

Does using anonymous function whenever possible reduces the memory usage and improves the overall performance in Dart?
Short Answer
No. It doesn't improve overall performance and also doesn't decrease memory usage. However the exact opposite might happen depending on the scenario.
Long Answer
Anonymous functions are the same as closures in Dart, and so will have a pointer(memory address) to the parent environment associated with it. Which means an additional variable with size equivalent to the bit-width of a pointer (in the corresponding platform) will be accompanying the anonymous function.
Memory
Here's how call to different types of functions work
Normal function: The arguments for the functions are the only values passed for the call.
Anonymous functions: The arguments for the functions are passed along with the pointer/reference to the parent's environment
Class method: A pointer/reference to the particular object instance is passed as the first argument along with the rest of the arguments.
Static Class method: This is equivalent to a normal function and the object instance of the class is not passed at all.
So, both class methods and anonymous functions have an extra variable, essentially a pointer, required to work. So "technically" this increases memory usage. However you don't have to worry about such things when you are using Dart. Because the extra memory required for anonymous functions and class methods is almost equivalent to when you add a new argument int newArg to a normal function or static class method.
If the anonymous function is executed right after it is declared, like (() {})(), then the pointer associated with it should be cleared in the next garbage collection sweep. This of course depends on the implementation and the scenario. If the anonymous function is stored in a variable or passed as an argument, then the lifetime of the pointer depends on the lifetime of that variable or argument.
Also, the pointer refers to the parent environment and because of this, the variables belonging to the parent scope, referred in the anonymous function will be kept alive even if the execution of the parent scope is complete. This in fact means that less memory is cleared in the next garbage collection sweep. The memory allocated for those referred variables will be cleared only when the anonymous function itself is not required anymore.
Performance
In the case of anonymous functions, there is also the need for lookup of parent-scoped variables used in the function body, that is the lookup for all the variables that are from the parent environment, this adds to compile-time or runtime depending on whether your dart code is AOT or JIT compiled.
But the same thing happens with normal class methods, as there is a need to lookup all class members used. (This doesn't happen in languages like Rust, Python... where there is a keyword like self or this representing the object instance that has to be explicitly mentioned)
Additional Context
Anonymous functions are otherwise referred to as lambdas or closures. There is actually a difference in definition between lambdas and closures
mathematically, and both of those can work as the other one depending on the use-case.
Lambdas are supposed to be functions that takes only one argument and has only one statement.
Closures are supposed to be functions that closes over the scope of its parent. Basically, closures can look for variables in the environment of its parent.
In Dart, there are no two entities separately known as lambdas and closures, instead there are closures. This is commonly seen in many programming languages, as they don't bother to keep a separation. By the way, the definition doesn't restrict a lambda from being a closure. And vice-versa.

Function which one must not shadow in Matlab

I am writing some helper functions for unit testing in Matlab. For that I need to overload Matlab functions, built-ins etc. In the documentation is written, that one shall not overload the function builtin. I also found out that one must not overload the lt operator, since it seems to get called by the UI all the time.
Is there a list of functions which one shall not overload, or do you know of any particular problems from overloading some specific functions?
Further Information:
My use case: I want to do mutation-testing and faul-injection.
in ther words, sometimes the called functions shall return wrong results or throw an error. If I overload the Matlab functions, I do not have to change the source code to do that.

Where to define typecast to struct in MATLAB OOP?

In the MATLAB OOP framework, it can be useful to cast an object to a struct, i.e., define a function that takes an object and returns a struct with equivalent fields.
What is the appropriate place to do this? I can think of several options:
Build a separate converter object that takes care of conversions between various classes
Add a function struct to the class that does the conversion to struct, and make the constructor accept structs
Neither option seems to be very elegant: the first means that logic about the class itself is moved to another class. On the other hand, in the second case, it provokes users to use the struct function for any object, which will in general give a warning (structOnObject).
Are there altenatives?
Personally I'd go with the second option, and not worry about provoking users to call struct on other classes; you can only worry about your own code, not that of a third-party, even if the third party is MathWorks. In any case, if they do start to call struct on an arbitrary class, it's only a warning; nothing actually dangerous is likely to happen, it's just not a good practice.
But if you're concerned about that, you can always call your converter method toStruct rather than struct. Or perhaps the best (although slightly more complex) way might be to overload cast for your class, accepting and handling the option 'struct', and passing any other option through to builtin('cast',....
PS The title of your question refers to typecasting, but what your after here is casting. In MATLAB, typecasting is a different operation, involving taking the exact bits of one type and reinterpreting them as bits of another type (possibly an array of the output type). See doc cast and doc typecast for more information on the distinction.
The second option sounds much better to me.
A quick and dirty way to get rid of the warning would be disabling it by calling
warning('off', 'MATLAB:structOnObject')
at the start of your program.
The solutions provided in Sam Roberts' answer are however much cleaner. I personally would go for the toStruct() method.

What is a callback in programming?

I have heard this term tossed around, can anybody explain what it means and what problem it solves. Also where does this originate from.
Simplified it's when you pass a function to another function, and that other function call you back using the function you passed.
It's useful for asynchronous programming, when events can happen at any time. Or for generic handling of certain functionality to make some algorithms more generic (for example in C++ you can pass a comparison function to the std::sort function, and your comparison function will be used to compare two items when sorting).

Do I conserve memory in MATLAB by declaring variables global instead of passing them as arguments?

I am new to MATLAB, it wasn't in the job description and I've been forced to take over for the person who wrote and maintained the code my company uses. Life's tough.
The guy from which I'm taking over told me that he declared all the big data vectors as global, to save memory. More specifically, so that when one function calls another function, he doesn't create a copy of the data when he passes it over.
Is this true? I read Strategies for Efficient Use of Memory, and it says that
When working with large data sets, be aware that MATLAB makes a temporary copy of an input variable if the called function modifies its value. This temporarily doubles the memory required to store the array, which causes MATLAB to generate an error if sufficient memory is not available.
It says something very similiar in Memory Allocation For Array #Function Arguments:
When you pass a variable to a function, you are actually passing a reference to the data that the variable represents. As long as the input data is not modified by the function being called, the variable in the calling function and the variable in the called function point to the same location in memory. If the called function modifies the value of the input data, then MATLAB makes a copy of the original array in a new location in memory, updates that copy with the modified value, and points the input variable in the called function to this new array.
So is it true that using global can be better? It seems a little sloppy to blithely declare all the large data as global, instead of making sure that none of the code modifies its input argument. Am I wrong? Does this really improve RAM usage?
In my experience, provided that none of the code modifies the large data, memory usage is the same, regardless of whether you use a global variable or an input argument, just like the Matlab docs say. Further information is in this blog post by a MathWorks employee.
There is quite a bit of folklore on performance issues in Matlab and not all of it is right. The internals of Matlab have changed quite a bit. It may be that in a previous version it's better to use a global variable.
This answer may be somewhat tangential, but an additional topic that bears mention here is the use of nested functions to manage memory.
As has already been established in other answers, there is no need for global variables if the data you are passing to the function is not modified (since it will be passed by reference). If it is modified (and is thus passed by value), using a global variable instead will save you memory. However, global variables can be somewhat "uncouth" for the following reasons:
You have to make a declaration like global varName everywhere you need them.
It can be conceptually a little messy trying to keep track of when and how they are modified, especially if they are spread across multiple m-files.
The user can easily break your code with an ill-placed clear global, which clears all global variables.
An alternative to global variables was mentioned in the first set of documentation you cited: nested functions. Immediately following the quote you cited is a code example (which I've formatted slightly differently here):
function myfun
A = magic(500);
setrowval(400, 0);
disp('The new value of A(399:401,1:10) is')
A(399:401,1:10)
function setrowval(row, value)
A(row,:) = value;
end
end
In this example, the function setrowval is nested inside the function myfun. The variable A in the workspace of myfun is accessible within setrowval (as if it had been declared global in each). The nested function modifies this shared variable, thus avoiding any additional memory allocation. You don't have to worry about the user inadvertently clearing anything and (in my opinion) it's a bit cleaner and easier to follow than declaring global variables.
The solution seems a bit strange to me. As you found out already, it shouldn't have significant impact on the memory usage if the called function does not modify the data array. However, if the called function modifies the data array, there's a functional difference: In one case (making the data array global), the change has an impact on the rest of the code, in the other case (passing it as reference) the modifications are only local and temporary.
I think you pretty much answered your own question, but a couple more references would be good here:
I made a video on this:
http://blogs.mathworks.com/videos/2008/09/16/new-location-and-memory-allocation/
Similar to what Loren spoke of here:
http://blogs.mathworks.com/loren/2006/05/10/memory-management-for-functions-and-variables/
-Dogu