Summary - Performance
- Dart course
- Advanced
- Lesson 78/83
- 5 min
Combine benchmark, Stopwatch and profiling to write a perf tool.
Summary - Performance
In this group we learned Dart's performance tools. benchmark measures code speed; Stopwatch is the built-in timer; ProcessInfo gives memory usage; caching (memoization) speeds up repeated computation; DevTools and Timeline are used for profiling.
In this summary we will write a small program that brings Stopwatch and the cached fib function together. The program starts a Stopwatch, computes cached fib(20), stops the Stopwatch and prints the result. This is a small example of an application's performance layer: measurement + optimization together.
Practice Stopwatch + memoized fib
Define the map final cache = <int, int>{}; (outside main). Write int fib(int n): if n < 2 return n; if cache.containsKey(n) return cache[n]!; else compute fib(n-1) + fib(n-2), store, return. In main start with final sw = Stopwatch()..start();, call final result = fib(20);, then sw.stop();. Print with print('fib(20): $result') and print('Stopwatch: ${sw.isRunning}').
Starter code
// define the cache map and the fib function
void main() {
// compute fib(20) with Stopwatch, print result and Stopwatch status
}Sample solution
final cache = <int, int>{};
int fib(int n) {
if (n < 2) return n;
if (cache.containsKey(n)) return cache[n]!;
final r = fib(n - 1) + fib(n - 2);
cache[n] = r;
return r;
}
void main() {
final sw = Stopwatch()..start();
final result = fib(20);
sw.stop();
print('fib(20): $result');
print('Stopwatch: ${sw.isRunning}');
}Expected output
fib(20): 6765 Stopwatch: false
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which class measures time?
- AES
- Stopwatch Correct answer
- Hmac
- bcrypt
Explanation: Stopwatch measures time; AES, Hmac or bcrypt are security tools.
2 Match the performance tools
| Term | Meaning |
|---|---|
Stopwatch |
Time |
fib |
Fibonacci |
cache |
Cache |
Timeline |
Profile |
3 Stopwatch status
print('Stopwatch: ${sw.____}');
print('Stopwatch: ${sw.isRunning}');
Explanation: sw.isRunning gives the running status of the Stopwatch.