Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 7c19b3cc authored by Yurii Zubrytskyi's avatar Yurii Zubrytskyi
Browse files

[res] Speed up a check of a resource name for int

Resources.getIdentifier(name) and Resources.getValue(name) both
first check if the passed name is actually an ID in a string
form, and does it with Integer.parseInt(). Most of the time it
isn't, and that's reported via Java exception. So the most
common use case involves an exception on a regular path.

This change adds a simple check to filter out all names that
don't look like a number, and only try parsing those that are
'int-like', i.e. <=10 digits. This speeds up the calls by more
than 2x, and gets rid of most of heap usages

Bug: 282215580
Test: build + presubmits
Change-Id: I1cd6be728f4e4bec04cb97729911c6a3fae0d010
parent d3ca7f8a
Loading
Loading
Loading
Loading
+17 −4
Original line number Diff line number Diff line
@@ -273,15 +273,28 @@ public class ResourcesImpl {
        throw new NotFoundException("String resource name " + name);
    }

    private static boolean isIntLike(@NonNull String s) {
        if (s.isEmpty() || s.length() > 10) return false;
        for (int i = 0, size = s.length(); i < size; i++) {
            final char c = s.charAt(i);
            if (c < '0' || c > '9') {
                return false;
            }
        }
        return true;
    }

    int getIdentifier(String name, String defType, String defPackage) {
        if (name == null) {
            throw new NullPointerException("name is null");
        }
        if (isIntLike(name)) {
            try {
                return Integer.parseInt(name);
            } catch (Exception e) {
                // Ignore
            }
        }
        return mAssets.getResourceIdentifier(name, defType, defPackage);
    }