0

I'm writing a JSON composer, but I'm not happy with the speeds I'm getting.

The input is Hash tables and/or object lists.

Here's a snippet of the code. 'de' is a DictionaryEntry from a Hash table and 'output' is the json string we are building.

if (de.Value.GetType() == typeof(Hashtable))
{
    output += RenderObject((Hashtable)de.Value, level + 1, format);
}

This is basically how my whole code is built.

My test-case right now is a List containing 10 000 hash tables, each with 4 key/value pairs of different types.

On a crappy desktop computer it generated the whole string in exactly 60 seconds. The output was 927 kB.

I'm looking for advice on optimizing it and input on what kind of speeds I should be happy with. A whole minute to generate a <1mb json string is too slow, I think.

4
  • if (de.Value is IDictionary) Commented Oct 25, 2011 at 14:12
  • 1
    Why are you re-inventing the wheel? Commented Oct 25, 2011 at 14:12
  • You may want to use a profiler to find the hot spots. To @SLaks point, though, there are lots of JSON serializers available already. Commented Oct 25, 2011 at 14:26
  • I have looked at all of the ones listed at JSON.org. None do exactly what I want, so I made my own parser and composer. Most of them are made to serialize and deserialize objects, which is good for storing data. I'm more interested in exchanging data and wanted something very similar to the PHP 5.3 json_decode() Commented Oct 25, 2011 at 14:35

1 Answer 1

4

You need to use a StringBuilder.
When recursing, you should append to the original StringBuilder; don't create a separate StringBuilder for each object.

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

2 Comments

Ok I did this and it took generation time of one of my tests from 120seconds to 0.046 seconds. I feel pretty stupid now :) Thanks for your answer.
It's always nice to get a 260,000% performance boost. However, you should re-use an existing library instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.