Question

I am developing an Android App called Smart Call Blocker which lets you enter a regex pattern and then retrieves incoming phone numbers and performs a match and then allows/rejects the call depending on whether the match was successful or not.

The pattern that a user enters is supposed to allow:

either a digit, or a dot (meaning don't care the digit at this position), 
or a range (e.g. [3-7]), or a set of digits (e.g. [2, 5, 8])

Now I have written code to manually compare the incoming phone number digit by digit with respect to the pattern and allow/reject a call accordingly. It is running in linear time (number of comparisons equal to the number of digits in the phone number).

Which should be faster and lighter for an android app?

  1. The manual method written by me.
  2. The regex library using its own Pattern.compile() and matches() etc methods.

And why and how?

EDIT:

I have pasted the code here. I am unable to do a proper benchmarking for the android OS, although I can do an execution time comparison on the two said ways as normal java programs on my system. But I don't think there would be any conclusion that can be made by just seeing the runtime of these programs on system than when ran on actual android device.

Was it helpful?

Solution

First, this isn't a good SO question because there's no way to provide references or test my answer with what you've given. So some answers based on theory:

Which should be faster and lighter for an android app?

Your code should be faster. Two reasons:

  1. It is "precompiled." The regex matcher compiles the pattern into an internal code of some kind (a bytecode or tree). This takes time. Your code runs with no such overhead.

  2. Most regex matchers - including the Java library's - use a general branch and bound search algorithm. Even if searching is never necessary (it always branches correctly), the capability to search introduces some small overhead.

So if your code is running slower than an equivalent regex, your code is not good. There is one caveat: In Android your code is probably written in Java, I am assuming the Android regex library is still Java code. It was last time I wrote to Android, but that's been several versions ago. The Android Java compiler is not yet as good as the native gcc. So if some optimization has been added, you might have to re-implement your code natively to do better than a regex.

Very important caveat and educated guess: Reading patterns from the file and compiling (if using regexes) should be done only once during app start-up. If you do this, the speed difference between your code and the regex method will be so tiny that it won't make a difference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top