简体   繁体   中英

What is the fastest way to retrieve values from String?

During my app development one performance question came to my mind:

I have a lot of lines of data that can looks like that:

  • !ANG:-0.03,0.14,55.31
  • !ANG:-0.03,-0.14,305.31
  • !ANG:-234.03,-0.14,55.31
  • in general: !ANG:float,float,float

Between those lines there are also "damaged" lines - they don't start with ! or are too short/have extra signs and so on.

To detect lines that are damaged at the begining I simply use

if(myString.charAt(0) != '!')//wrong string

What I can do to detect lines that are damaged at the end? It is very important to mention that I need not only to check if the line is correct but also get those 3 float numbers to use it later.

I've found three options for this:

  • use regexp
  • split twice (first ":" and second ",") and count elements
  • use Scanner class

I am not sure which one of this (or maybe there are other) methods will be the best from the performance point of view. Can you please give me some advice?

EDIT:

After some comments I see that it is worth to write how damage lines an look:

  • NG:-0.03,0.14,55.31
  • .14,55.31
  • !ANG:-0.03,0.14,
  • !A,-0.02,-0.14,554,-0.12,55

It is quite difficult to talk about number of lines because I am getting them from readings from other device so I get packets of around 20 lines at a time with a frequency of 50Hz.

What I've found out so far is the big drawback of using scanner - for each line I need to create new object and after some time my device is starting to get short on resources.

Benchmark them, then you will know.

The likely fastest way is to write your own tiny state machine to match your format and find the float boundaries. Theoretically a regex will have the same performance, but it's likely to have additional overhead.

As an intermediate solution I'd do something like that :

private static class LineObject {
    private float f1, f2, f3;
}

private LineObject parseLine(String line) {
    LineObject obj = null;
    if (line.startsWith("!ANG:")) {
        int i = line.indexOf(',', 5);
        if (i != -1) {
            int j = line.indexOf(',', i+1);
            if (j != -1) {
                try {
                    obj = new LineObject();
                    obj.f1 = Float.parseFloat(line.substring(5, i));
                    obj.f2 = Float.parseFloat(line.substring(i+1, j));
                    obj.f3 = Float.parseFloat(line.substring(++j));
                } catch (NumberFormatException e) {
                    return null;
                }
            }
        }
    }
    return obj;
}

After you can copy/paste only usefull jdk code of startsWith, indexOf and parseFloat in your own state machine...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM