Question

I was writing some helper methods for our testers around the IWebDriver in .NET, and started wondering whether there was any point in have a method to get an element by ID when you can use a CSS selector to also get the element by ID.

I would assume that, in the end, a request for CSS "#myelement" will be optimised away to document.getElementById("myelement") anyway.

Is there a performance difference? Should we bother using By.Id and By.Name when we can use CSS selectors to accomplish the same thing?

Was it helpful?

Solution

By.cssSelector() is faster than By.id().

The method to find elements using By.id() actually utilizes xpath:

    @Override
    public List<WebElement> findElements(SearchContext context) {
      if (context instanceof FindsById)
        return ((FindsById) context).findElementsById(id);
      return ((FindsByXPath) context).findElementsByXPath(".//*[@id = '" + id
          + "']");
    }

    @Override
    public WebElement findElement(SearchContext context) {
      if (context instanceof FindsById)
        return ((FindsById) context).findElementById(id);
      return ((FindsByXPath) context).findElementByXPath(".//*[@id = '" + id
          + "']");
    }

Where as By.cssSelector uses the CSS engine. CSS is faster than xpath, ergo, By.cssSelector will operate faster than By.id

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top