Skip to main content

Speeding Up Selenium WebDriver Tests with Efficient Locators

Speeding Up Selenium WebDriver Tests with Efficient Locators

Key takeaways

  • By.id, By.name and a CSS selector on an id were within noise of each other (about 3 ms per lookup in the test below); an XPath on an attribute cost about 2 to 3 ms more.
  • Almost all of those milliseconds are the WebDriver round trip, not the search: the same lookups run inside the page took under 0.4 ms.
  • A 100-lookup test pays a fraction of a second for the choice of locator. Waits, page loads and network cost orders of magnitude more.
  • Pick the locator for stability: an id first, then a short CSS selector, then XPath only where CSS cannot say it.

The fastest Selenium locator is By.id, but on a current Chrome the gap to CSS and XPath is a few milliseconds per lookup, so choose by stability first. This post measures it instead of repeating the folklore. The numbers come from one machine and one synthetic page, and they say how big the gap is, not that it is the same on your application.

Which Selenium locator is fastest?

I timed driver.findElement for six locators that all find the same input, on a local page with a 2,000-row table (about 10,000 elements). Each locator ran 300 timed calls after 50 warm-up calls, and the whole sequence was repeated three times. The table shows the median per call, in milliseconds.

LocatorRound 1Round 2Round 3
By.id("field1999")3.262.982.95
By.name("field1999")3.433.003.12
By.cssSelector("#field1999")3.222.663.67
By.cssSelector("[data-test='f1999']")3.794.764.85
By.xpath("//input[@data-test='f1999']")5.126.705.69
By.xpath("/html/body/table/tbody/tr[2000]/td/div/input")3.805.655.06

Setup: Selenium 4.51.0 (Java, compiled and run with Temurin 17), Chrome 156.0.8078.47 headless with the matching chromedriver 156, macOS 15.7 on an Apple Silicon Mac, page loaded from a local file, 2026-10-23. Read the table loosely: the spread between rounds of the same locator (2.66 to 3.67 ms for the CSS id selector) is as large as some of the gaps between locators. What holds across the rounds is the order: id, name and CSS-on-id at the bottom, an attribute selector slightly higher, XPath on top.

The honest summary is that an XPath lookup on this page cost about 2 to 3 ms more than an id lookup. A test that finds 100 elements pays roughly a quarter to a third of a second for that, against the seconds a single page load or a wait can take. Do not rewrite a working suite to chase it.

Why are the differences so small?

Each findElement call is an HTTP request from your test to chromedriver, then a command to the browser, then a response, and that round trip is the roughly 3 ms floor in the table. The search inside the browser is a small part of it. Running the same lookups in the page itself with performance.now() (2,000 repetitions each) gave:

Lookup in the pageTime per call
document.getElementById0.0002 ms
document.getElementsByName0.0002 ms
document.querySelector("[data-test='f1999']")0.045 ms
document.evaluate with the XPath on the attribute0.37 ms

So the browser does find ids orders of magnitude faster than it evaluates XPath, which is where the old advice came from, but both are far below the cost of the round trip. The selenium.dev guidance says the same in words: ids “tend to work very quickly”, a well-written CSS selector is the preferred choice when there is no id, and XPath tends to be slower and harder to debug (selenium.dev, test practices, “Encouraged: locators”, read 2026-10-23). The measurement above puts a size on “slower”.

One thing the numbers do not cover: this page was small and static. A selector that forces the browser to walk a very large DOM, or a lookup that runs in a loop of thousands of calls, is where locator choice could start to show. Measure that case on your own page before changing anything.

How can you time your own locators?

The class below is the whole benchmark in miniature. It uses Selenium Manager (built into Selenium 4.6 and later), so there is no driver download. Point it at a page of yours and change the locators.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.Arrays;

public class LocatorTiming {
    static double medianMs(WebDriver driver, By by, int runs) {
        double[] t = new double[runs];
        for (int i = 0; i < runs; i++) {
            long start = System.nanoTime();
            driver.findElement(by);
            t[i] = (System.nanoTime() - start) / 1e6;
        }
        Arrays.sort(t);
        return t[runs / 2];
    }

    public static void main(String[] args) {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless=new");
        WebDriver driver = new ChromeDriver(options);
        try {
            driver.get(args[0]); // for a local file: file:///path/to/page.html
            By[] locators = {
                By.id("email"),
                By.cssSelector("[data-test='email']"),
                By.xpath("//input[@data-test='email']")
            };
            for (By by : locators) medianMs(driver, by, 50); // warm-up
            for (By by : locators) {
                System.out.printf("%-45s %.2f ms%n", by, medianMs(driver, by, 300));
            }
        } finally {
            driver.quit();
        }
    }
}

Run it more than once and compare medians, not single calls, because one lookup can swing by several milliseconds. This snippet compiles against Selenium 4.51.0; the table in this post came from the same approach with the six locators listed and three rounds. A later single run of this snippet, while other jobs were loading the machine, read 8.5 ms (id), 8.0 ms (CSS) and 11.3 ms (XPath): absolute numbers move with machine load, the XPath gap of a few milliseconds stayed.

Which locator should you use?

Choose by how long the locator will keep working, since speed hardly separates them:

  1. Use an id when the element has one that does not change between builds.
  2. Otherwise use a short CSS selector, ideally on a dedicated test attribute such as data-test, which survives restyling and markup changes.
  3. Use XPath when CSS cannot express it, for example matching on visible text or walking up to a parent. Avoid long positional paths like /html/body/table/tbody/tr[2000]/td/div/input: they were no faster in the table and break the moment someone adds a wrapper element.
  4. Ask developers for ids or test attributes. A locator that needs a paragraph of explanation is a sign the page needs one.

The locator strategies themselves, with code for each, are in how to locate web elements with Selenium WebDriver. If your tests are slow, the bigger wins are usually waiting correctly (explicit and implicit waits), not repeating page loads, and checking how fast the page itself responds. For that last part, LoadFocus can load test the site your Selenium suite runs against, since a slow server will make every locator look slow.

Older write-ups, including an earlier version of this post, singled out XPath in Internet Explorer and recommended Firebug and FirePath for building expressions. Those tools are discontinued, and the measurement here is Chrome only; if you still test in another browser, run the timing class there.

Frequently Asked Questions

Which locator is fastest in Selenium?

By.id, with By.name and a CSS selector on an id effectively tied in the test above, at about 3 ms per lookup on Selenium 4.51 and Chrome 156. XPath on an attribute was about 2 to 3 ms slower on that page.

Is XPath slower than CSS in Selenium?

Slightly, in the measurement above and in selenium.dev’s own wording, but the gap is a few milliseconds per lookup. Choose between them on readability and stability.

Does the choice of locator change my test run time?

Rarely in a way you can see. A suite with 1,000 lookups would differ by a few seconds at most between the fastest and slowest locator here, while page loads and waits usually cost far more.

How do I make Selenium tests faster?

Remove fixed sleeps in favour of explicit waits, avoid reloading pages you do not need to reload, run tests in parallel, and keep the application under test responsive. Locator tuning comes last.

Sources

Chris

Head of Content at LoadFocus

Chris leads content and oversees development across the services this blog covers. The guides and tool comparisons here come out of the same decisions that shape what ships.

Weekly tips right in your inbox.

Don’t miss out on the latest testing tips and tricks, tools and news related to software testing.

Already +20,000 members in the list.

The Load Testing Platform with AI That Explains Your Results

Load test websites and APIs from 25 cloud regions, monitor page speed and uptime, and get AI analysis that explains your results in plain English.

Cloud load testing, website speed and API monitoring in one place.

Hi there! Can I share a cool thing I'm working on with you?

A software testing newsletter that sparks joy.

Our goal is to create helpful content for software developers and testers.

If you're not into it, you can unsubscribe instantly.