Parsing Performance (If, TryParse, Try-Catch)

后端 未结 5 1829
抹茶落季
抹茶落季 2020-11-27 19:00

I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering i

5条回答
  •  攒了一身酷
    2020-11-27 19:24

    Option 1: Will throw an exception on bad data.
    Option 2: SomethingIsValid() could be quite expensive - particularly if you are pre-checking a string for Integer parsability.
    Option 3: I like this.  You need a null check afterwards, but it's pretty cheap.
    Option 4 is definitely the worst.
    

    Exception handling is comparatively expensive, so avoid it if you can.

    In particular, bad inputs are to be expected, not exceptional, so you shouldn't use them for this situation.

    (Although, before TryParse, It may have been the best option.)

提交回复
热议问题