Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium: Is there a performance difference between By.Id("myelement") and By.Css("#myelement")?

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?

like image 517
Richiban Avatar asked Jan 16 '14 10:01

Richiban


1 Answers

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

like image 117
ddavison Avatar answered Nov 06 '22 08:11

ddavison