1

I'm writing a custom Json serializer to improve the perf of my service. And yes, I did consider Json.NET, servicestack, DataContractJsonSerializer, etc before I made the decision. My objects are flat with simple .NET types and I wanted to avoid the overhead of a much bigger library.

Anyways, here is where I run into a small problem. I have the code to serialize DateTime -

    var epoch = new DateTime(1970, 1, 1, 0, 0, 0);
    sb.Append("\"\\/Date(");
    SerializeNumber((time - epoch).TotalMilliseconds, sb);
    sb.Append(")\\/\"");

And this works great, except I can't quite get it to match the default .NET Json serializer in the output.

.NET serializer 
"\\/Date(1328057884253)\\/\"
Custom serializer
"\\/Date(1328057884253.04)\\/\"

Hmm, so I tried making my conversion less precise and switching to (int)TotalSeconds instead of milliseconds and that gives me this -

.NET serializer
"\\/Date(1328054810067)\\/\"
Custom serializer
"\\/Date(1328054810)\\/\"

I'm guessing that this wouldn't be a big deal but it would be nice to get my unit tests passing against the default .NET serializer just for sanity. Any ideas?

Thanks.

4
  • I'm hoping for a followup in the comments that shows your performance delta with your hand-rolled library. Commented Feb 1, 2012 at 19:04
  • By considering servicestack.text did you have benchmarks that it was too slow on? or was the 120kb dependency-free .dll too big? Commented Feb 1, 2012 at 20:57
  • servicestack wasn't slow, it just wasn't an acceptable solution for our client for various reasons. Note that I'm only serializing the events which is fairly trivial, compared to deserializing which is a beast. My local profiler shows 4.x% improvement over the default .NET serializer while using my hand crafted serializer. Commented Feb 2, 2012 at 1:11
  • I meant to say close to a 4x improvement Commented Feb 2, 2012 at 2:06

2 Answers 2

2

The Property TotalMilliseconds is of type double. You could just cast it into a long instead of using the TotalSeconds method which of course doesn't return the same value...

var epoch = new DateTime(1970, 1, 1, 0, 0, 0);
sb.Append("\"\\/Date(");
SerializeNumber((long)(time - epoch).TotalMilliseconds, sb);
sb.Append(")\\/\"");

edit: as Kosh said in comments, prefer long to int to avoid capacity overflow.

Sign up to request clarification or add additional context in comments.

1 Comment

well, I had to cast it to long to avoid an overflow but that did it.
0

couldnt you just truncate the result?

Math.Truncate((time - epoch).TotalMilliseconds)

http://msdn.microsoft.com/de-de/library/c2eabd70.aspx

or maybe better round it. dont know what the JsonSerializer would do.

Math.Round((time - epoch).TotalMilliseconds, 0)

http://msdn.microsoft.com/de-de/library/75ks3aby.aspx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.