Faster version of Convert.ChangeType

前端 未结 5 1377
北荒
北荒 2021-01-02 04:12

In an application that I have, I am doing quite frequent calls to Convert.ChangeType in order to convert a value to a dynamically loaded type.

However

5条回答
  •  一向
    一向 (楼主)
    2021-01-02 04:28

    I'm not aware of any other functionality within the framework itself for changing Types other than the Convert.ChangeType function (and explicit casts, obviously).

    For this, I think the only other way to improve this is to roll your own ChangeType function that is specifically optimized for your particular situation (if possible).

    You mention that you're working with a limited number of Types, perhaps you're dealing with one Type more than the others? Is so, your ChangeType function could be optimized to attempt this specific conversion first, and only trying others if failing. You mention trying a switch-style block of code, and this same approach (trying the most frequently used Type first) could be applied to that. As to whether it will be faster would depend upon your data that you're processing (and the frequency/variability of the Types you're converting to/from) and the only real way to measure this is to try it and profile it in comparison with the Convert.ChangeType methodology.

    One interesting link if you're looking to roll-your-own functionality is on Peter Johnson's blog:

    Convert.ChangeType doesn't handle nullables

    Be sure to read all of the comments to the post also.

提交回复
热议问题