Search code examples
javaandroidstaticglobal-variableslocal-variables

Performance wise is better to use global static variables or local variables?


I have an app that continuously check for matches into a text. Snippet:

public boolean method()
    {
        if(Pattern.compile(Pattern.quote("TEST1"), Pattern.CASE_INSENSITIVE).matcher(text).find())
            return true;
        if(Pattern.compile(Pattern.quote("TEST2"), Pattern.CASE_INSENSITIVE).matcher(text).find())
            return true;
        return false;
    }

Since this method gets called a lot, I thought what if I make static global variables instead of creating Pattern inside the method each time gets called. Therefore:

     private static final Pattern TEST_1 = Pattern.compile(Pattern.quote("TEST1"), Pattern.CASE_INSENSITIVE);
    private static final Pattern TEST_2 = Pattern.compile(Pattern.quote("TEST2"), Pattern.CASE_INSENSITIVE);

 public boolean method()
    {
        if(TEST_1.matcher(text).find())
            return true;
        if(TEST_2.matcher(text).find())
            return true;
        return false;
    }

Would doing this increase the performance in the long run and, most importantly, prevent the app from being killed by the Android OS?


Solution

  • Would doing this increase the performance in the long run

    Yes. You are avoiding object instantiation and cutting down on garbage collection needs.

    prevent the app from being killed by the Android OS?

    No.