Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Improve caching performance #406

Merged
merged 1 commit into from
Jan 19, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 12 additions & 17 deletions app/src/main/java/io/appium/uiautomator2/model/ElementsCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
import androidx.test.uiautomator.UiObject2;
import androidx.test.uiautomator.UiSelector;

import java.util.Objects;

import io.appium.uiautomator2.common.exceptions.ElementNotFoundException;
import io.appium.uiautomator2.common.exceptions.StaleElementReferenceException;
import io.appium.uiautomator2.model.internal.CustomUiDevice;
Expand Down Expand Up @@ -131,8 +129,9 @@ public AndroidElement get(String id) {
"A valid cached element identifier must be provided. Got null instead");
}

AndroidElement resultElement;
synchronized (cache) {
AndroidElement resultElement = cache.get(id);
resultElement = cache.get(id);
if (resultElement != null) {
// It might be that cached UI object has been invalidated
// after AX cache reset has been performed. So we try to recreate
Expand All @@ -146,13 +145,14 @@ public AndroidElement get(String id) {
resultElement = restore(resultElement);
}
}
if (resultElement == null) {
throw new ElementNotFoundException(
String.format("The element identified by '%s' is not present in the cache " +
"or has expired. Try to find it again", id));
}
return resultElement;
}

if (resultElement == null) {
throw new ElementNotFoundException(
String.format("The element identified by '%s' is not present in the cache " +
"or has expired. Try to find it again", id));
}
return resultElement;
}

public AndroidElement add(Object element, boolean isSingleMatch) {
Expand All @@ -163,17 +163,12 @@ public AndroidElement add(Object element, boolean isSingleMatch, @Nullable By by
return add(element, isSingleMatch, by, null);
}

public AndroidElement add(Object element, boolean isSingleMatch, @Nullable By by, @Nullable String contextId) {
public AndroidElement add(Object element, boolean isSingleMatch, @Nullable By by,
@Nullable String contextId) {
AndroidElement androidElement = toAndroidElement(element, isSingleMatch, by, contextId);
synchronized (cache) {
for (AndroidElement cachedElement : cache.snapshot().values()) {
if (Objects.equals(androidElement, cachedElement)) {
return cache.get(cachedElement.getId());
}
}

cache.put(androidElement.getId(), androidElement);
return androidElement;
}
return androidElement;
}
}