Java – which is faster, int to string or string to int?

This seems to be a fairly basic problem. I apologize in advance

I'm writing an Android application that uses a set of predefined numbers I'm currently working on int values, but at some point I may also need to use float and double values

These figures apply to two things First, I need to display them to the user. I need a string (I'm creating a custom view and drawing a string on canvas) Second, I need to use them in a calculator, which obviously needs to be int (or float / double)

Since the numbers are the same, whether they are used as string or int, I only want to store them once (if I need to change either, it will also reduce errors; I only need to change them in one place)

My question is: should I store them as string or int? Is it faster to write int as string or parse int from string? My intuition tells me that parsing requires more time / resources, so I should store them as int. am I right?

Solution

In fact, your intuition may be wrong (I emphasize the possibility, please refer to the comments on measurement below) To convert a string to an integer requires a series of multiplication / addition operations To convert an integer to a string, you need division / modulus It is likely that the former is faster than the latter

But I want to point out that you should measure, not guess! The landscape is full of algorithmic groups that rely on false assumptions

I also want to point out that unless your calculator does a lot of calculations every second (and I say millions or even billions), the difference is almost certainly irrelevant

In the vast majority of user interactive applications, 99% of computer time is spent waiting for users to do something

My advice is to do something that makes your life easier as a developer and worry about performance if (and only) it becomes a problem And, for clarity, I suggest that storing them in native form (not strings) is the easiest for calculators

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>