String to Number转换中的性能问题 [英] Performance issue in String to Number conversion

查看:160
本文介绍了String to Number转换中的性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有空格分隔的字符串,其间包含数字:

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.

所以,我的问题是:


  1. 我们如何改善以下代码中的表现?

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

我们是否有其他方法可以编写以下代码来解决问题?

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

代码:

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"));
    }
} 


推荐答案

这是我能想到的最快的:

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.

结果与 davecom的基准测试

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

这篇关于String to Number转换中的性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆