Hacker News new | past | comments | ask | show | jobs | submit login

Thanks -- added an issue for the linear search https://github.com/rottytooth/rot8000/issues/2 -- will place a limit on chars in that textbox as well



For reference, I created an optimized implementation and tested it with a string containing all characters from U+0000 to U+FFFF in order and got the following times. The original implementation took 5202.766 ms, the optimized implementation took 0.079 ms for a speed-up of about 65858. That this is pretty close to 65536 is probably a reflection of the cost for the linear search through almost that number of characters and the test pattern I choose but I am not entirely sure, intuitively I would have expected a factor of 0.5 in there to account for the average case. But I am too lazy right now to do the math.


I've updated it to use a hashtable and the tests run quite a lot faster


I took the array approach which should be still faster because it avoids the hash calculations. Just build an array Char[65536] containing at every index i the character the character i should be mapped to. Rotator.Rotate() then simply becomes the following where Rotator.map is the precomputed array. Probably very similar to an implementation using a hash table. I also got rid of the string builder but did not profile the difference. If one uses a string builder it would most likely help to specify the capacity in the constructor call so that the internal array does not have to be resized repeatedly as the result is constructed and grows in length.

  public static String Rotate(String input)
  {
    var result = new Char[input.Length];

    for (var index = 0; index < input.Length; index++)
    {
      result[index] = Rotator.map[input[index]];
    }

    return new String(result);
  }


Limiting the text box will protect you against the most naive DoS attacks, but you need some kind of limit at the API level (request size, etc.). Never trust the client.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: