Selenium Locators Speed Test: Fastest to Slowest

When writing Selenium automation tests, selecting an efficient locator strategy directly impacts how quickly and reliably your tests run. We all want our tests to be fast, stable, and easily maintainable. A common question testers often ask is: “Which locator performs the fastest in Selenium?”

In this article, we’ll experimentally verify the performance of various locator strategies – ID, Name, CSS Selector, and XPath. Additionally, we’ll delve deeper into XPath itself, comparing different XPath expressions based on complexity.

When automation scripts scale to hundreds or thousands of elements, each millisecond counts. Slow locators:

  • Increase test execution time
  • Create flakiness and instability in tests
  • Reduce productivity (debugging slow/unstable tests takes more time)

Hence, it’s smart to know the performance characteristics of different locators to build optimized and robust test suites.

For reference, here are popular locators offered by Selenium WebDriver:

  • By ID
  • By Name
  • By Class Name
  • CSS Selector
  • XPath ( Absolute and Relative )

The webpage we’ve chosen for this experiment is our TextField demo page: https://testkru.com/Elements/TextFields.

Here, we will find the highlighted element below:

Text field demo page

Here are the different locators for finding the above element

TypeLocator
IDBy.id(“lastNameWithPlaceholder”)
NameBy.name(“lastName”)
CSS SelectorBy.cssSelector(“input#lastNameWithPlaceholder”)
Class NamelastNameWithPlaceholder
Relative XPathBy.xpath(“//input[@id=’lastNameWithPlaceholder’]”)
Absolute XPathBy.xpath(“/html/body/div/div/div/div[2]/div[2]/input”)

We took several steps to ensure accurate and consistent results:

  • Ensured stable network connectivity during the entire testing process.
  • Conducted a ‘warm-up run’ beforehand to allow the browser cache to stabilize
  • Averaged results across multiple runs to reduce random variations and achieve consistent, reliable timing measurements. In this specific test, we’ll locate the same element 500 times using an identical locator.
  • Confirmed no background processes disrupted or interfered with system resources during testing.
  • We’ll carry out the experiment on both Chrome and Firefox browsers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static double measureLocatorAccurately(WebDriver driver, By locator, int repetitions) {
 
    long totalTimeNs = 0;
    int success = 0;
 
    try {
        Thread.sleep(250); // short pause to standardize environment after reload
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
 
    for (int i = 0; i < repetitions; i++) {
 
        try {
            long startTime = System.nanoTime();  // start time
            driver.findElement(locator);
            long endTime = System.nanoTime(); // end time
            totalTimeNs += (endTime - startTime);
            success++;
        } catch (Exception e) {
            System.out.println("Locator failed on iteration " + (i+1) + ": " + locator);
        }
    }
 
    if (success == 0) {
        System.out.println("Locator failed entirely: " + locator);
        return -1.0;
    }
     
    return (totalTimeNs / success) / 1_000_000.0;
}

This function calculates and returns the average time (in milliseconds) taken to locate an element using a given locator.

We can then call the above method for different locators.

1
2
3
By locator = By.id("lastNameWithPlaceholder");
double avgTime = measureLocatorAccurately(driver,locator, 500);
System.out.printf("%-20s: %.2f ms%n", "ID", avgTime);
1
2
3
By locator = By.name("lastName");
double avgTime = measureLocatorAccurately(driver,locator, 500);
System.out.printf("%-20s: %.2f ms%n", "ID", avgTime);
1
2
3
By locator = By.cssSelector("input#lastNameWithPlaceholder");
double avgTime = measureLocatorAccurately(driver,locator, 500);
System.out.printf("%-20s: %.2f ms%n", "ID", avgTime);
1
2
3
By locator = By.className("lastNameWithPlaceholder");
double avgTime = measureLocatorAccurately(driver,locator, 500);
System.out.printf("%-20s: %.2f ms%n", "ID", avgTime);
1
2
3
By locator = By.xpath("//input[@id='lastNameWithPlaceholder']");
double avgTime = measureLocatorAccurately(driver,locator, 500);
System.out.printf("%-20s: %.2f ms%n", "ID", avgTime);
1
2
3
By locator = By.xpath("/html/body/div/div/div/div[2]/div[2]/input");
double avgTime = measureLocatorAccurately(driver,locator, 500);
System.out.printf("%-20s: %.2f ms%n", "ID", avgTime);

Here is the whole code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
 
import java.time.Duration;
 
public class SeleniumLocatorBenchmarkWithWait {
 
    public static void main(String[] args) {
 
        WebDriver driver = new ChromeDriver();
 
        // Open URL
        driver.get("https://testkru.com/Elements/TextFields");
 
        // Use explicit wait (WebDriverWait) to wait until the page loads fully.
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("lastNameWithPlaceholder")));
 
        By locator = By.id("lastNameWithPlaceholder");
        double avgTime = measureLocatorAccurately(driver,locator, 500);
        System.out.printf("%-20s: %.2f ms%n", "ID", avgTime);
 
        driver.quit();
    }
 
    public static double measureLocatorAccurately(WebDriver driver, By locator, int repetitions) {
 
        long totalTimeNs = 0;
        int success = 0;
 
        try {
            Thread.sleep(250); // short pause to standardize environment after reload
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
        for (int i = 0; i < repetitions; i++) {
 
            try {
                long startTime = System.nanoTime();
                driver.findElement(locator);
                long endTime = System.nanoTime();
                totalTimeNs += (endTime - startTime);
                success++;
            } catch (Exception e) {
                System.out.println("Locator failed on iteration " + (i+1) + ": " + locator);
            }
        }
 
        if (success == 0) {
            System.out.println("Locator failed entirely: " + locator);
            return -1.0;
        }
 
        return (totalTimeNs / success) / 1_000_000.0;
    }
}

Here is the result of the above code on different locators –

TypeTime taken
ID2.80 ms
Name2.87 ms
CSS Selector2.84 ms
Class Name2.88 ms
Relative XPath2.91 ms
Absolute XPath3:00 ms

We observed that locating elements by ID was the fastest method, while using Absolute XPath was the slowest.

Here is the ranking of locators from the fastest to the slowest in Selenium:

ID > CSS Selector > Name > Class Name > Relative XPath > Absolute XPath

Note: Despite careful control, minor variability due to some unknown factors can’t be fully avoided.

Running the same experiment on FirefoxDriver gives the following result –

TypeTime taken
ID0.80 ms
Name0.84 ms
CSS Selector0.82 ms
Class Name0.87 ms
Relative XPath0.88 ms
Absolute XPath0.87 ms

From this, we can draw some observations:

  • Locating elements took slightly less time in Firefox compared to Chrome.
  • ID remained the fastest locator, although the difference wasn’t significant.
  • Overall, the differences between the various locator types were not substantial enough to draw a definitive conclusion.

Clearly, the ID locator is the fastest among Selenium’s locator strategies, closely followed by CSS Selectors. XPath typically requires more time due to its underlying parsing mechanism, especially for complex expressions.

This is it. We hope that you have liked the article. If you have any doubts or concerns, please write to us in the comments or mail us at admin@codekru.com.

Related Articles
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *