Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a string in Haxe

Tags:

string

haxe

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);
    }
}
like image 263
wof Avatar asked Feb 18 '23 13:02

wof


1 Answers

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):

  • A: 0.030ms
  • B: 0.032ms (worst)
  • C: 0.006ms (5 times faster than A)
  • D: 0.002ms (best, 16 times faster than A)

250 characters string measurements (calculated from 500,000 iterations and divided accordingly):

  • A: 0.996ms
  • B: 1.326ms (still worst)
  • C: 0.166ms (6 times faster than A)
  • D: 0.044ms (best, 22 times faster than A)

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.

like image 116
the_yellow_logo Avatar answered Feb 21 '23 03:02

the_yellow_logo