facebook-csharp-sdk/simple-json — pull request #45 by niik (2014-02-23 21:11:49+00:00)
Title: Micro-optimize string serialization

While profiling an extremely high-write scenario in one of my apps I found that a decent amount of time was being spent serializing (read: escaping) strings. My objects consisted almost exclusively of strings so I went in to see if there was any perf gains to be made.

I started out by optimizing the happy path of the string not needing to be escaped at all (ie no unsafe characters) and that change (cece3e4) is probably pretty uncontroversial. Then I went to town on the loop, still optimizing for there being fewer unsafe characters than safe, buffering up stringbuilder writes to ranges of safe characters. This lead to a small perf hit for extremely short string and a pretty decent speed increase for slightly largers strings.

## Benchmark

This compares two scenarios, one where the string doesn't contain any unsafe characters (which I would guess is the case for most strings going through SimpleJson) and one where the string contains a percentage of unsafe characters. Each runs 1000000 iterations of serialize and runs GC collect in between each test to make sure garbage left over from the last run doesn't affect the outcome of the second.

![string-perf](https://f.cloud.github.com/assets/634063/2241362/7ef19c08-9ccd-11e3-821e-460c8ceecf87.png)

The test string with unsafe characters have a uniform distribution of unsafe characters which perhaps isn't that probable in a real-world scenario but it _shouldn't_ significantly influence the outcome of the benchmark.

Worth noting is that while the percentages here are quite nice the wall time decrease isn't massively impressive. Long story short the stuff that's in there now is quick enough for the vast majority of scenarios. I just wanted to say that so you can consider whether or not its worth accepting or not. If you decide it's not worth it please do still consider cece3e4 as a separate change because that's a happy path which will have real impact on serialization.