Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance issue in String to Number conversion

I have space separated string containing numbers in between like:

"abc123 ws32wd3 y3tg43 5tga89 a1a"

I have to parse the string to get the numbers from each token and then sum up all the digits extracted from tokens. I have written below code, but what I think is, if there is huge string, then there might be performance issue.

So, my questions are:

  1. How can we improve the performance in below code?

  2. Do we have another way to write the below code to solve the problem?

Code:

public class TestSum {

    public static int doSum(String str){
        String[] sArray = str.split(" ");
        char[] chr = null;
        String temp;
        String number = "";
        int sum=0;
        for(String s : sArray){
            chr = s.toCharArray();
            for(char c : chr){
                temp = String.valueOf(c);
                if(isNum(temp)){
                    number = number + temp;
                }           
            }
            sum = sum + Integer.parseInt(number);
            number="";
        }       
        return sum;
    }

    public static boolean isNum(String nStr){   
        try{
            Integer.parseInt(nStr);
            return true;
        }catch(NumberFormatException nfe){
            return false;
        }       
    }

    public static void main(String[] args) {
        System.out.println("Sum is "+ TestSum.doSum("abc123 ws32wd3 y3tg43 5tga89 a1a"));
    }
} 
like image 267
Juns Avatar asked Apr 16 '26 08:04

Juns


1 Answers

This is the fastest I could think of:

public static int getSum(String str) 
{
    int sum = 0;
    int exp = 1;      
    for (int i = str.length() - 1; i >= 0; i--) 
    {
        final char c = str.charAt(i);
        if (c >= '0' && c <= '9')
        {
            sum += (c - '0') * exp;
            exp *= 10;
        }
        else
        {
            exp = 1;
        }
    }
    return sum;
}

It iterates through string from right to left. Thanks to that, when it "sees" a digit it can add appropriate value, depending on the decimal position "seen" in the number.

Benchmark using Caliper

Results are different than in davecom's benchmark:

AUTHOR       RUNTIME (NS)   HOW MANY TIMES FASTER THAN JUNS
-----------------------------------------------------------
Adam              66.221                                600
Old              579.873                                 70
Prabhakaran   20,012.750                                  2 (2x faster than Juns)
Juns          39,681.074                                  1
like image 110
Adam Stelmaszczyk Avatar answered Apr 18 '26 20:04

Adam Stelmaszczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!