B
B
Bone2021-11-29 11:05:20
go
Bone, 2021-11-29 11:05:20

golang. Which is faster than strings.Contains or json.Unmarshal?

Hello! I have a client that sends requests to an api and returns a "raw" (just text) response. Responses from api come in the form of json. Sometimes api may return an error, relatively speaking, in the form {"error_code": 1, "error_msg": "some error"}. The client must understand that an error has returned and redirect the response from the api to the error channel.
The obvious solution is to do json.Unmarshal in the client and check for the existence of the error_code field, but as far as I understand, this is not the easiest operation, especially since api responses can contain very long jsons.
What if we look for an occurrence of error_code in the text using strings.Contains and only if it is found, then do json.Unmarshal. Will it help improve performance?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2021-11-29
@Bone

This will increase performance, strings.Contains is much faster than json.Unmarshal
But it will decrease reliability, because error_code will be searched everywhere, it will not necessarily be a field name.

R
Roman Mirilaczvili, 2021-11-29
@2ord

I agree with Alexander Pavlyuk .
If you want to save money on cases where the answer is quite weighty, but just getting some fields is enough, then you can try https://github.com/tidwall/gjson

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question