Using split () is slower than some other methods, especially if the string is large enough.
The tests below are performed on my computer for the Neko target, compiled with Haxe 2.10. First, check the 6-digit string ("abcdef").
Implementing A with split / join takes about (0.030ms):
var s = "abcdef"; var a = s.split(''); a.reverse(); s = a.join('');
Implementation B runs approximately equally slowly, if not more slowly, than solution A (0.032ms):
var s = "abcdef"; var s2 = ""; for (i in -s.length+1...1) s2 += s.charAt(-i);
Implementing C is 5 times faster than implementing 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));
Implementation D appears faster, 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.
Measurement readings on a Neko with a 6-character string (calculated from 500,000 iterations and accordingly divided):
- A: 0.030ms
- B: 0.032ms (worst)
- C: 0.006 ms (5 times faster than A)
- D: 0.002ms (best, 16 times faster than A)
250 characters of string measurements (calculated from 500,000 iterations and accordingly divided):
- A: 0.996ms
- B: 1.326ms (still worse)
- C: 0.166ms (6 times faster than A)
- D: 0.044ms (best, 22 times faster than A)
The results show that the implementation of A becomes slower and slower with respect to D as the row size grows (which means that its complexity function O (n) is worse).
For these reasons, I recommend the implementation of D.