Skip to content

Instantly share code, notes, and snippets.

@Luckey-Elijah
Last active June 16, 2022 18:14
Show Gist options
  • Save Luckey-Elijah/76a3c149bdca960c51892f5d74de4e43 to your computer and use it in GitHub Desktop.
Save Luckey-Elijah/76a3c149bdca960c51892f5d74de4e43 to your computer and use it in GitHub Desktop.
switch_vs_if_else
import 'dart:math';
/// A small test to test the performance of
/// `if-else` statements to `switch-case` statements.
///
/// The same [Stopwatch] and [Random] are use for the entire test.
/// Each one-to-one execution of a test (5 in total) uses a new list of
/// random values to iterate through to create identical scenarios.
///
///
/// Compiled
/// ```
/// $ dart compile exe main.dart && ./main.exe
/// ```
///
/// JIT
/// ```
/// $ dart run main.dart
/// ```
void main() {
final iterations = 5;
final random = Random();
final stopwatch = Stopwatch();
final results = Iterable.generate(
iterations,
(index) {
return runner(
stopwatch,
Iterable.generate(
10000000,
(_) => Option.values[random.nextInt(3)],
));
},
).fold<TestResult>(
const TestResult(0, 0),
(prev, current) => prev + current,
);
print(results.toString());
}
enum Option { one, two, three } // arbitrary object
class TestResult {
const TestResult(this.switchTime, this.ifElseTime);
final int switchTime;
final int ifElseTime;
operator +(TestResult other) =>
TestResult(other.switchTime + switchTime, other.ifElseTime + ifElseTime);
@override
String toString() => '''
TestResult(
switch : ${switchTime}ms
if-else: ${ifElseTime}ms
)
''';
}
TestResult runner(
Stopwatch stopwatch,
Iterable<Option> listOfOptions,
) {
final ones = <Option>{};
final twos = <Option>{};
final threes = <Option>{};
void tearDown() {
ones.clear();
twos.clear();
threes.clear();
stopwatch.reset();
}
stopwatch.start();
for (final option in listOfOptions) {
if (option == Option.one) {
ones.add(option);
} else if (option == Option.two) {
twos.add(option);
} else if (option == Option.three) {
threes.add(option);
}
}
stopwatch.stop();
final ifElseTime = stopwatch.elapsedMilliseconds;
tearDown();
stopwatch.start();
for (final option in listOfOptions) {
switch (option) {
case Option.one:
ones.add(option);
break;
case Option.two:
twos.add(option);
break;
case Option.three:
threes.add(option);
break;
}
}
stopwatch.stop();
final switchTime = stopwatch.elapsedMilliseconds;
tearDown();
return TestResult(switchTime, ifElseTime);
}
/// System
/// ```
/// $ dart --version
/// > Dart SDK version: 2.17.1 (stable) (Tue May 17 17:58:21 2022 +0000) on "macos_x64"
/// ```
/// Results:
/// ```
/// $ dart compile exe main.dart && ./main.exe
/// > TestResult(
/// > switch : 1770ms
/// > if-else: 1815ms
/// > )
/// ```
/// ```
/// $ dart run main.dart
/// > TestResult(
/// > switch : 1945ms
/// > if-else: 1831ms
/// > )
/// ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment