5
\$\begingroup\$

I am using Selenium Webdriver via Java. My method clicks on a filter check box (eg. make, model, etc.), that is passed in, from a modal.

When running my method in my test class, via ChromeDriver, it seems to go pretty slow and rightfully so since I am making a lot of tiny network calls for getText(). How can I optimize its performance?

public void selectFilter(String filter) {
 List<WebElement> filters = driver.findElements(selector.someWebElement());
 Map<String, WebElement> mapFilters = new HashMap();
 for (int i = 0; i < filters.size(); i++) {
 String key = filters.get(i).getText();
 WebElement value = filters.get(i).findElement(By.cssSelector("a"));
 mapFilters.put(key, value);
 }
 mapFilters.get(filter).click();
 }
Quill
12k5 gold badges41 silver badges93 bronze badges
asked Dec 10, 2015 at 15:59
\$\endgroup\$
0

1 Answer 1

6
\$\begingroup\$

The method appears to have some pointless operations.

You loop over a List<WebElement>, to build a Map<String, WebElement>, where the key of the map is the text in a WebElement in the list. But you use only one key in the map, the String filter parameter received by the method. As such, you don't need a map at all.

This implementation is (almost) equivalent:

public void selectFilter(String filter) {
 List<WebElement> filters = driver.findElements(selector.someWebElement());
 WebElement value = null;
 for (int i = 0; i < filters.size(); i++) {
 String key = filters.get(i).getText();
 if (key.equals(filter)) {
 value = filters.get(i).findElement(By.cssSelector("a"));
 }
 }
 if (value != null) {
 value.click();
 }
}

I say almost equivalent, because I added a missed null-check.

To further improve the performance, it would be better to refine this call:

 List<WebElement> filters = driver.findElements(selector.someWebElement());

As apparently it fetches many elements that don't match the String filter parameter of the method.

Quill
12k5 gold badges41 silver badges93 bronze badges
answered Dec 10, 2015 at 18:54
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Oh wow, I was over complicating things. This is why codereview is an awesome site. Thank you very much! Once I reach 15 reputation points I will make sure to upvote your answer. \$\endgroup\$ Commented Dec 10, 2015 at 21:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.