Last active
August 19, 2018 12:19
-
-
Save lrhn/8515b26b4d4b4807d24bbe7cb36a8f91 to your computer and use it in GitHub Desktop.
String Concatenation Benchmark
This file contains hidden or 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
const int count = 100000; | |
void test(String s) {} | |
void main() { | |
Stopwatch t = new Stopwatch(); | |
// Run more than once to account for JIT compilation and optimization. | |
for (int i = 0; i < 3; i++) { | |
// USING STRING | |
{ | |
int e = 0; | |
int c = 0; | |
t.reset(); | |
t.start(); | |
do { | |
String s = ''; | |
for (int i = 0; i < count; i += 1) { | |
s = s + '-$i'; | |
test(s); | |
} | |
c++; | |
e = t.elapsedMicroseconds; | |
} while (e < 2000000); | |
t.stop(); | |
print("String 1: ${c * 1000000 / e} /s"); | |
} | |
// USING STRING 2 | |
{ | |
int e = 0; | |
int c = 0; | |
t.reset(); | |
t.start(); | |
do { | |
String s = ''; | |
for (int i = 0; i < count; i += 1) { | |
s = '$s-$i'; | |
test(s); | |
} | |
c++; | |
e = t.elapsedMicroseconds; | |
} while (e < 2000000); | |
t.stop(); | |
print("String 2: ${c * 1000000 / e} /s"); | |
} | |
// USING STRINGBUFFER | |
{ | |
int e = 0; | |
int c = 0; | |
t.reset(); | |
t.start(); | |
do { | |
StringBuffer b = new StringBuffer(); | |
for (int i = 0; i < count; i += 1) { | |
b.write('-$i'); | |
test(b.toString()); | |
} | |
c++; | |
e = t.elapsedMicroseconds; | |
} while (e < 2000000); | |
t.stop(); | |
print("StringBuffer 1: ${c * 1000000 / e} /s"); | |
} | |
// USING STRINGBUFFER 2 | |
{ | |
int e = 0; | |
int c = 0; | |
t.reset(); | |
t.start(); | |
do { | |
StringBuffer b = new StringBuffer(); | |
for (int i = 0; i < count; i += 1) { | |
b..write('-')..write(i); | |
test(b.toString()); | |
} | |
c++; | |
e = t.elapsedMicroseconds; | |
} while (e < 2000000); | |
t.stop(); | |
print("StringBuffer 2: ${c * 1000000 / e} /s"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment