Created
January 27, 2018 07:29
-
-
Save dudeofawesome/49b3292bd274d22399273013ab88afd3 to your computer and use it in GitHub Desktop.
Benchmark char comparison methods in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:benchmark_harness/benchmark_harness.dart'; | |
const testString = 'this is a test string that you can ignore.'; | |
class BareRunesForLoopBenchmark extends BenchmarkBase { | |
const BareRunesForLoopBenchmark() : super('s.runes'); | |
static void main() => new BareRunesForLoopBenchmark().report(); | |
// The benchmark code. | |
void run() { | |
var res = 0; | |
for (final r in testString.runes) { | |
if (r == 115) res++; | |
} | |
res; | |
} | |
} | |
class RegExpBenchmark extends BenchmarkBase { | |
const RegExpBenchmark() : super('RegExp.allMatches(s)'); | |
static void main() => new RegExpBenchmark().report(); | |
// The benchmark code. | |
void run() { | |
new RegExp('s').allMatches(testString).length; | |
} | |
} | |
class StringArrayForLoopBenchmark extends BenchmarkBase { | |
const StringArrayForLoopBenchmark() : super('s[i] == "s"'); | |
static void main() => new StringArrayForLoopBenchmark().report(); | |
// The benchmark code. | |
void run() { | |
var res = 0; | |
for (var i = 0; i < testString.length; i++) { | |
if (testString[i] == 's') res++; | |
} | |
res; | |
} | |
} | |
class RunesToFromCharCodeBenchmark extends BenchmarkBase { | |
const RunesToFromCharCodeBenchmark() : super('s.runes == fromCharCode'); | |
static void main() => new RunesToFromCharCodeBenchmark().report(); | |
// The benchmark code. | |
void run() { | |
var res = 0; | |
for (final r in testString.runes) { | |
if (new String.fromCharCode(r) == 's') res++; | |
} | |
res; | |
} | |
} | |
class CodeUnitsBenchmark extends BenchmarkBase { | |
const CodeUnitsBenchmark() : super('s.codeUnits'); | |
static void main() => new CodeUnitsBenchmark().report(); | |
// The benchmark code. | |
void run() { | |
var res = 0; | |
for (final r in testString.codeUnits) { | |
if (r == 115) res++; | |
} | |
res; | |
} | |
} | |
main() { | |
// Run benchmarks. | |
RunesToFromCharCodeBenchmark.main(); | |
BareRunesForLoopBenchmark.main(); | |
StringArrayForLoopBenchmark.main(); | |
CodeUnitsBenchmark.main(); | |
RegExpBenchmark.main(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment