Search code examples
javastringbigdecimal

Is performing mathematical operations on String variable a good idea?


Is it a good idea to hold the numeric values in String variable in an object (also passing in methods and returning as String) and later while only operating it convert in BigDecimal and operate?

The intention to use in method signature and pojo's is that operation can be performed in double or any other type the implementor prefers to

For e.g.

public String operate(String value1, String value2){
    BigDecimal val1 = new BigDecimal(value1);
    BigDecimal val2 = new BigDecimal(value2);
    return val1.multiply(val2).toString();
}

Or it is just an overhead?

Would it affect performance?


Solution

  • It's a bad idea from two standpoints:

    1. All of the operation will require you to translate from/to string representation
    2. Memory overhead is enormous.

    Consider this example. An ordinary int occupies 4 bytes in memory. An int represented as a String can occupy up to 72 bytes:

    • 16 bytes -- object overhead,
    • 4 bytes -- cached hash code
    • 8 bytes -- reference to char array
    • 24 + 2 * 10 bytes -- char array itself (10 digits max)
    • up to 8 bytes for padding

    It is 18 (!) times more than a primitive representation of an int.