Title: Speed up background thread Android
Tags: java;android
Question: My Android application has taken me to a point where I need to run a brute-force method in a background thread. I need this to run incredibly fast.
In this context, the brute force system is trying to determine if three numbers can be used to mathematically solve for one number.
Example: num1 = 1 num2 = 2 num3 = 3. It tries all mathematical operations until it discovers a correct equation that equals a preset number.
My current code is already running on a background thread, but it is SOOOOOO slow.
Here it is:
```new Thread(new Runnable() {
            @Override
            public void run() {

                Expression expressionToTest = new Expression();

                double result;

                while (expressionToTest.calculate() != number) {
                    expressionString = bruteForcer.computeNextCombination();
                    Expression expression = new Expression(expressionString);
                    System.out.println(&quot;Trying: &quot; + expressionString);
                    result = expression.calculate();
                    System.out.println(&quot;Expression: &quot; + String.valueOf(result));
                    expressionToTest = expression;
                }

            }
        }).start();



    }

```
It is probably not the best option in the world to brute force in Java, but is what I must do. No other solutions have worked for me.
Taking into consideration what Graziano said, I came up with this code:
```new Thread(new Runnable() {
        @Override
        public void run() {
            // Allocate the Expression object, using the 3 parameter in input
            // The allocation already calculates the first result
            Expression expression = new Expression(&quot;&quot;);

            while (expression.calculate() != 3.0) {
                // Make a step forward on operators, and calculate the result
                expressionString = bruteForcer.computeNextCombination();
                expression.setExpressionString(expressionString);

                // No new allocations into this &quot;while&quot; cycle!
                // You should pay attention to not allocate new variables during
                // any step and calculation also into Expression object.
                // All the allocations should be done into the constructor, that is called outside.

                System.out.println(&quot;Trying: &quot; + expressionString);
                System.out.println(&quot;Expression&quot; + String.valueOf(expression.calculate()));
            }
        }
    }).start();
```
If you would care to look at this and comment what you think, that would be much appreciated!
Per request of @Graziano: Mathparser Expression object
I cannot really make any major modifications to this code... =(
Problem solved.

Comment: Thanks guys. The Expression type is from MxParser (http://mathparser.org/). It is what validates the equation after the brute-force class generates the combination.

Comment: The only character sets the brute-force algorithm takes into account are: +-()*^/sqrt. Sqrt is the square root function.

Comment: @Graziano could you give me an example of that?

Comment: As a tip, you could speed up the thread execution by avoiding memory allocations. Try to allocate out of the while cycle and reuse the same object for all the iterations. Try also to remove the System.out.println lines and repeat the test in order to verify that they don't impact the performances too much.

Comment: Also you can change the priority of the thread to a higher one using setPriority(). You can check out [this for more details](https://developer.android.com/reference/android/os/Process#THREAD_PRIORITY_URGENT_DISPLAY)

Comment: Where does the `Expression` type come from? Given that you're working with a very limited set of operations (how big depends on what's included in "all operations"), it's probably better to code specific code to try those combinations than to use a general-purpose evaluator. That would remove the string generation and parsing time from the loop which is probably significant and also massively reduce memory pressure (and thus garbage collection time).

Comment: While you're running this on a thread, it would likely help to parallelize the attempts such that you can try multiple brooksangela@example.org.


Here is another answer: You should find a way to write a code like the following one:
```new Thread(new Runnable() {
    @Override
    public void run() {
        double rightResult = YOUR RESULT;
        // Allocate the Expression object, using the 3 parameter in input
        // The allocation already calculates the first result
        Expression expression = new Expression(double num1, double num2, double num3);

        while (expression.result != rightResult) {
            // Make a step forward on operators, and calculate the result
            expression.computeNextCombination();

            // No new allocations into this &quot;while&quot; cycle!
            // You should pay attention to not allocate new variables during
            // any step and calculation also into Expression object.
            // All the allocations should be done into the constructor, that is called outside.

            System.out.print(&quot;Trying: &quot; + expression.toString + &quot; = &quot; + expression.result);
        }
    }
}).start();
```
You should avoid to allocate any variable or object during any step and calculation also in Expression object. All the allocation should be done into the ```Expression``` constructor.
You can increment the performances of the thread also by setting a higher priority, like @mohammed-ahmed rightly wrote, but if you choose a higher priority you might have impacts on the user interface.

Comment for this answer: STILL SLOOWWWWW! =(
Comment for this answer: I believe I have found the issue... Running expression.calculate in the while loop logic is slowing it down. Im going to find a way to replace this somehow and get back to you.
Comment for this answer: I was able to replace the .calculate function. My code now runs super-fast!
Comment for this answer: Please post the code of your Expression object, so that we can make some checks

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 7, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:03/15/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><android>', 'Title': 'Speed up background thread Android', 'ViewCount': 76, 'id': 71475636, 'user_AboutMe': None, 'user_AccountId': None, 'user_DisplayName': None, 'user_Reputation': None, 'user_Views': None, 'user_id': None}}