Which is fast comparison: Convert.ToInt32(stringValue)==intValue or stringValue==intValue.ToString()

后端 未结 8 2065
执念已碎
执念已碎 2021-02-13 18:34

While developing my application i came across some comparison stuff here was it:

    string str = \"12345\";
    int j = 12345;
    if (str == j.ToString())
             


        
8条回答
  •  青春惊慌失措
    2021-02-13 19:17

    Yikes, you show your domain logic as being inside your profiling loop so you weren't testing the time difference between the Convert and ToString versions of your code; you were testing the combined time of the conversion plus the execution of your business logic. If your business logic is slow and dominates the conversion time, of course you will see the same time in each version.

    Now, with that out of the way, even worrying about this until you know that it's a performance bottleneck is premature optimization. In particular, if executing your domain logic dominates the conversion time, the difference between the two will never matter. So, choose the one that is most readable.

    Now, as for which version to use: You need to start by specifying exactly what you're testing. What are your inputs? Is "007" ever going to be an input? Is "007" different than the integer 7? Is "1,024" ever going to be an input? Are there localization concerns?

提交回复
热议问题