Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# JSON parsing vs substring

I have a program that is making web request, then breaking down the response. The content type is JSON, and Im currently treating the response as a string and using substring to decode it.

string bidnumber = "buyNowPrice";
int startbid = tradetemp.IndexOf(bidnumber) + 13;
int bidlength = 10;
string bidtemp = tradetemp.Substring(startbid, bidlength);
string endbid = ",";
int endbid2 = bidtemp.IndexOf(endbid);
int bidlength2 = endbid2;
string bidtmp = bidtemp.Substring(0, bidlength2);
long bid = Convert.ToInt64(bidtmp);

Im doing this for about 5 variables, and constantly doing it over and over. The question is would using JSON parsing be more efficient (faster) over my current code. Using a JSON parse would make my code cleaner, but speed is priority here.

like image 241
ChrisB Avatar asked Apr 20 '26 16:04

ChrisB


1 Answers

Use JSON parsing. One of the biggest mistakes that you can make as a programmer is to say that speed matters and write long, hideous code because of it. There are a couple problems with this approach.

  1. How much does speed matter? If you can eliminate 70% of your written code in exchange for 10ms of performance, is that acceptable? You can't know the tradeoff without implementing a well-written solution and seeing it for yourself.

  2. It is not necessarily the things that you think are draining performance that will drain performance. Writing code to be fast doesn't necessarily solve performance problems because you need to test its performance.

  3. How much headache are you prepared to suffer in exchange for "speed"? Again, you don't know how much speed before you benchmark, but poorly-written code, or just even long and messy code can considerably increase the cost of maintaining your program. Don't underestimate this.

I strongly recommend you use the JSON.NET library included by default in VS 2012. I have used it a fair bit and have been quite impressed overall. It is clean and simple to use. Implement it and then benchmark. I think you'll be impressed.

like image 136
Levi Botelho Avatar answered Apr 23 '26 07:04

Levi Botelho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!