Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster, int to String or String to int?

Tags:

java

android

This may seem like a fairly basic question, for which I apologise in advance.

I'm writing an Android app that uses a set of predefined numbers. At the moment I'm working with int values, but at some point I will probably need to use float and double values, too.

The numbers are used for two things. First, I need to display them to the user, for which I need a String (I'm creating a custom View and drawing the String on a Canvas). Second, I need will be using them in a sort of calculator, for which they obviously need 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 (this will also reduce errors if I need to change any of them; I'll only need to change them in the one place).

My question is: should I store them as String or as int? Is it faster to write an int as a String, or to parse an int from a String? My gut tells me that parsing would take more time/resources, so I should store them as ints. Am I right?

like image 364
David John Welsh Avatar asked Jul 27 '11 12:07

David John Welsh


People also ask

What is converting int to string?

The Integer. toString() method converts int to String. The toString() is the static method of Integer class.

Can you convert string to int or float?

Strings can be converted to numbers by using the int() and float() methods.

Can you pass int to long?

Java int can be converted to long in two simple ways:This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.


1 Answers

Actually, your gut may be wrong (and I emphasise may, see my comments below on measuring). To convert a string to an integer requires a series of multiply/add operations. To convert an integer to a string requires division/modulo. It may well be that the former is faster than the latter.

But I'd like to point out that you should measure, not guess! The landscape is littered with the corpses of algorithms that relied on incorrect assumptions.

I would also like to point out that, unless your calculator is expected to do huge numbers of calculations each second (and I'm talking millions if not billions), the difference will be almost certainly be irrelevant.

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

My advice is to do whatever makes your life easier as a developer and worry about performance if (and only if) it becomes an issue. And, just to clarify, I would suggest that storing them in native form (not as strings) would be easiest for a calculator.

like image 87
paxdiablo Avatar answered Sep 23 '22 15:09

paxdiablo