问题描述:

I have 3 ways in which I could do this

JToken jEmail = jObject["emails"];

email = (string)jEmail["preferred"];

or

email = jEmail["preferred"].ToString();

or

email = jEmail["preferred"] == null ? null : (string)jEmail["preferred"];

So safely doing error handling is null or empty string, vs. performance... what is the preferred of the 3 above???

网友答案:

Your three examples have three different behaviors. Depending on which behavior you want, you should take the one that works:

  1. email = (string)jEmail["preferred"];

    I'm not certain, but I believe this will throw a NullReferenceException if "preferred" is missing. You might get away with it since string is a reference type. This would certainly fail if you were casting to int, for instance. See my comment on #3.

  2. email = jEmail["preferred"].ToString();

    This will definitely throw a NullReferenceException if "preferred" is missing, as you can't do null.ToString().

  3. email = jEmail["preferred"] == null ? null : (string)jEmail["preferred"];

    This will work either way. Be aware that callers may assume that email is never null, in which case they may throw NullReferenceException when trying to access it.

Choose which behavior you want, then implement it. Don't do it for performance, though, since you have no idea at this point whether you will be improving performance. Performance tuning must be done by measuring performance, and only then tuning it.

网友答案:

Per the above answer - I agree with.

This is benign in nature from JObject .... Newtonsoft.Json.Linq.JObject / .JToken ...0

email = (string)jEmail["preferred"];

However, you are welcome to use the ternary of below

 email = jEmail["preferred"] == null ? null : (string)jEmail["preferred"];

Not sure you will gain anything. You will end up with carpal tunnel as it appears not necessary, but depends on your end goal.

Performance... don't worry about it in this issue.

相关阅读:
Top