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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With