What are other options to reverse string in Haxe? I present mine (simple, clear and beginner like):
class ReverseString {
public static function main() {
Sys.println("Enter some words: ");
// Lets read some input!
var someWord = Sys.stdin().readLine();
// Split string to array, reverse string, and join again
var stringArray:Array<String> = someWord.split("");
stringArray.reverse();
var reversedString = stringArray.join("");
// And finally, enjoy the reversed string:
Sys.print("Reversed word looks like this: ");
Sys.println(reversedString);
}
}
Using split() is slow compared to some other methods, especially if the string is big enough.
The tests below are done on my computer for Neko target, compiled with Haxe 2.10. Let's first test for a 6-characters string ("abcdef").
Implementation A with split/join takes about (0.030ms):
var s = "abcdef";
var a = s.split('');
a.reverse();
s = a.join('');
// s contains "fedcba"
Implementation B runs about equally slow if not even slower than solution A (0.032ms):
var s = "abcdef";
var s2 = "";
for (i in -s.length+1...1)
s2 += s.charAt(-i);
// s2 contains "fedcba"
Implementation C is 5 times faster than implementation A (0.006ms):
import StringBuf;
using StringTools;
var s = "abcdef";
var s2 = new StringBuf();
for (i in -s.length+1...1)
s2.add(s.charAt(-i));
// s2.toString() contains "fedcba"
Implementation D appears the fastest, about 16 times faster than implementation A (0.002ms):
import StringBuf;
using StringTools;
var s = "abcdef";
var s2 = new StringBuf();
for (i in -s.length+1...1)
s2.addChar(s.fastCodeAt(-i));
// s2.toString() contains "fedcba"
// if introducing var s3 = s2.toString() it then takes from 0.003 to 0.004ms total
// so this still seems the fastest on Neko.
Measurements recap on Neko with a 6-characters string (calculated from 500,000 iterations and divided accordingly):
250 characters string measurements (calculated from 500,000 iterations and divided accordingly):
Results suggest implementation A gets slower and slower relatively to D as the size of the string grows (meaning its complexity function O(n) is worse).
For those reasons I recommend implementation D.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With