Effect of Anonymous function in performance in Dart - flutter

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.

Related

What is the benefit of defining enumerators as a DUT?

The main goal of defining enumerators is to assign a variable to some numbers and their equal strings as I understand.
We can define var a as an enum everywhere in the initializing section of our Program or Function Block like this:
a:(start,stop,operate);
tough I don't know why we can't see that in tabular view but there there is a big question that:
What is the benefit of defining enumerators as a DUT?
There are 3 main benefits for me:
You can use the same enum in multiples function blocks
You can use TO_STRING on enums declared as DUTs (After enabling it with {attribute 'to_string'} Infosys
You can use refactoring on names of each component, which is impossible with local enums
When defining an enum as a DUT it is available everywhere in your code (global scope).
This is helpful in many cases, but in general it is not good programming practice to have a lot of stuff available in the global scope.
Here is a bit elaboration on the topic.
In addition to the above, one benefit is that if you are using an enumeration for something like FB states, you will be able to see the descriptive status name when the program is running (READING, WRITING, WAITING, ERROR, etc.).
You can see it in the variable declarations section, in-line with your code, or in the watch window. You don’t have to remember what status number was defined in your state machine.
This benefit comes with local enumerations or DUT (global) enumerations.
In addition to other good points already made, there is another big advantage to enumerations : you can use the enumeration as the type of a variable, and when you do that, the compiler will (if {attribute 'strict'} is used in the enumeration declaration, which it probably should) refuse an assignment to that variable of a value that is not allowed by the enumeration.
In other words, you get rid of a whole class of failure modes where the variable ends up having an invalid value due to some coding mistake the compiler cannot catch.
It takes a trivial amount of time to create an enumeration, and it has benefits on many levels. I would say the real question is why not use them whenever a fixed list of meaningful values needs to be expressed.

Where are Global Functions & Variables stored in Swift?

From my understanding, the Stack is used to store value types (like Enumerations and Structures) and variables which are referenced to objects (like class instances) in the Heap. Furthermore, the Stack also holds function calls with their respective parameters and the like in a LIFO manner.
In C, there are 4 generic memory segments (Heap, Stack, Data, Code) where the Data segment(s) usually store the global and static variables which implies a completely separate aspect of memory where they are stored and managed, but I do believe Java handles it differently (with some magic on the part of the JVM).
How/where would a variable be stored if I declared a global variable in Swift? Would this be different if I simply played around with a Playground file, for example, compared to declaring a global/static variable/function in a project module in XCode?

define class inside method from a performance POV

I have a method that need return a Iterator. Then I defined a CustomIterator class inside that method and create instance of it as the return value.
It looks fine because only that method need to know about CustomIterator. But I'm afraid if this will produce too many Class instance as scala's type system is path-related.
Each class declaration will produce exactly one class file (that is, provided it does not contain inner classes or anonymous functions itself), so you shouldn't worry about that. Moreover, unless your program is supposed to run in a limited environment, additional classes won't cause any performance problems. In any case, you should profile your program before attempting such premature optimizations.
I'm not sure what you mean by "path-related type system". Is it path-dependent types? If so, this is a completely unrelated concept which exists in Scala type system only and does not affect actual class generation.

Why to use empty parentheses in Scala if we can just use no parentheses to define a function which does not need any arguments?

As far as I understand, in Scala we can define a function with no parameters either by using empty parentheses after its name, or no parentheses at all, and these two definitions are not synonyms. What is the purpose of distinguishing these 2 syntaxes and when should I better use one instead of another?
It's mostly a question of convention. Methods with empty parameter lists are, by convention, evaluated for their side-effects. Methods without parameters are assumed to be side-effect free. That's the convention.
Scala Style Guide says to omit parentheses only when the method being called has no side-effects:
http://docs.scala-lang.org/style/method-invocation.html
Other answers are great, but I also think it's worth mentioning that no-param methods allow for nice access to a classes fields, like so:
person.name
Because of parameterless methods, you could easily write a method to intercept reads (or writes) to the 'name' field without breaking calling code, like so
def name = { log("Accessing name!"); _name }
This is called the Uniform Access Principal
I have another light to bring to the usefulness of the convention encouraging an empty parentheses block in the declaration of functions (and thus later in calls to them) with side effects.
It is with the debugger.
If one add a watch in a debugger, such as, say, process referring for the example to a boolean in the focused debug context, either as a variable view, or as a pure side-effect free function evaluation, it creates a nasty risk for your later troubleshooting.
Indeed, if the debugger keeps that watch as a try-to-evaluate thing whenever you change the context (change thread, move in the call stack, reach another breakpoint...), which I found to be at least the case with IntelliJ IDEA, or Visual Studio for other languages, then the side-effects of any other process function possibly found in any browsed scope would be triggered...
Just imagine the kind of puzzling troubleshooting this could lead to if you do not have that warning just in mind, because of some innocent regular naming. If the convention were enforced, with my example, the process boolean evaluation would never fall back to a process() function call in the debugger watches; it might just be allowed in your debugger to explicitly access the () function putting process() in the watches, but then it would be clear you are not directly accessing any attribute or local variables, and fallbacks to other process() functions in other browsed scopes, if maybe unlucky, would at the very least be very less surprising.

Function pointer and normal function

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.