Is there a difference between wrapping the entire function and only wrapping the actual changes with setState()?
-
wrapping the entire function
setState(() { if (switchValueAdd) { valueAdd.text = (int.parse(num1) + int.parse(num2)).toString(); } else { valueAdd.text = ''; } });
-
wrapping only actual changes
if (switchValueAdd) {
setState(() {
valueAdd.text = (int.parse(num1) + int.parse(num2)).toString();
});
} else {
setState(() {
valueAdd.text = '';
});
}
Is there any difference in terms of performance between the above two code snippets?
Any help will be appreciated!
Also, with if-else statements, does ‘else’ cost as much memory as ‘if’?
In other words, is ‘else’ basically the same as ‘if’ but checking if otherwise is true?
Thank you for your effort and time in advance!
3
Answers
It is not difference.
setState
called only in one case (from if or else, not from both). But if you will have to write readable code, use first variant because it is more readable. And statements is not a high-performance operation.You can also simplify thin:
You can refresh state after executing all code of function so, it will reduce refresh build many times and improve performance of app.
Functionally, putting non-asynchronous code within the setState or putting it outside will result in very close to the same result. What you should try to avoid is having a huge block of code within the setState as this could be hard to read.
If you look at the source code for the
setState
method, it is just calling the function and doing a few asserts, so if you are doing the same amount of calls to it, it shouldn’t have any appreciable difference. Theoretically, it could be very slightly slower if you are accessing local variables from within the closure, as those variables (or at least the references to them) could need to be copied through the stack into the function, but the actual overhead that will result in would need someone with a more complete understanding of dart’s compiler for various platforms to fully explore.Realistically, in terms of actual real-world performance, it’s very unlikely to matter. There are probably other optimizations in your code which would result in much larger performance variance than this.
Also, from the
setState
documentation:I would focus more on legibility in this case – whichever version you find easier to read is probably the one that will serve you best.
I’d probably write it like this: