DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Express Hibernate Queries as Type-Safe Java Streams
  • Functional Approach To String Manipulation in Java
  • How to Automatically Detect Multiple Cybersecurity Threats from an Input Text String in Java
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)

Trending

  • Microsoft Foundry Agent Debugging Dashboard with Microsoft Fabric Eventhouse, KQL, Docker and Grafana
  • Two AI Agents, One Database: Solving Concurrent Updates With Optimistic Locking
  • Chaos Engineering and Kafka In Action: Topic Level Idempotence and Retry Check
  • Gitember: Building a Git Client Beyond Commit, Push, and Pull

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Hibernate Validator vs Regex vs Manual Validation: Which One Is Faster?

Hibernate Validator vs Regex vs Manual Validation: Which One Is Faster?

Inspired by coding for a performance backend competition, this article follows a test to find the fastest validator for Java applications.

By 
Fernando Boaglio
·
Jun. 03, 24 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

While I was coding for a performance back-end competition,  I tried a couple of tricks, and I was wondering if there was a faster validator for Java applications, so I started a sample application.

I used a very simple scenario: just validate the user's email.

Controller With Hibernate Validator

Hibernate Validator needs an object to put its rules to, so we have this:

Java
 
public record User(
    @NotNull
    @Email
    String email
){}


This is used in the HibernateValidatorController class, which uses the jakarta.validation.Validator (which is just an interface for the Hibernate Validator implementation):

Java
 
@RestController
@Validated
public class HibernateValidatorController {

    @Autowired
    private Validator validator;

    @GetMapping("/validate-hibernate")
    public ResponseEntity<String> validateEmail(@RequestParam String email) {


Using the validate method, we can check if this user's email is valid and get a proper HTTP response.

Java
 
var user = new User(email);
var violations = validator.validate(user);
if (violations.isEmpty()) {
  return ResponseEntity.ok("Valid email: 200 OK");
} else {
  var violationMessages = new StringBuilder();
  for (ConstraintViolation<User> violation : violations) {
    violationMessages.append(violation.getMessage()).append("\n");
  }
  return ResponseEntity.status(HttpStatus.BAD_REQUEST)
     .body("Invalid email: 400 Bad Request\n" + violationMessages.toString());
}


Controller With Regular Expression

For validation with regex, we need just the email regex and a method to validate:

Java
 
static final String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@(.+)$";

boolean isValid(String email) {
  return email != null && email.matches(EMAIL_REGEX);
}


The regexController class just gets an email from the request and uses the isValid method to validate it.

Java
 
@GetMapping("/validate-regex")
public ResponseEntity<String> validateEmail(@RequestParam String email) {

  if (isValid(email)) {
    return ResponseEntity.ok("Valid email: 200 OK");
  } else {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid email: 400 Bad Request");
  }

}


Controller With Manual Validation

We won't use any framework or libs to validate, just plain old String methods:

Java
 
boolean isValid(String email) {
  if (email == null) return false;
  int atIndex = email.indexOf("@");
  int dotIndex = email.lastIndexOf(".");

  return atIndex > 0 && dotIndex > atIndex + 1 && dotIndex < email.length() - 1;
}


The programmaticController class just gets an email from the request and uses the isValid method to validate it. 

Java
 
@GetMapping("/validate-programmatic")
public ResponseEntity<String> validateEmail(@RequestParam String email) {

  if (isValid(email)) {
    return ResponseEntity.ok("Valid email: 200 OK");
  } else {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid email: 400 Bad Request");
  }

}


Very Simple Stress Test

We are using Apache JMeter to test all 3 APIs. 

Our simulation runs with 1000 concurrent users in a loop for 100 times sending a valid email each request.

Hibernate API Thread Group

Running it on my desktop machine got similar results for all APIs, but the winner is Hibernate Validator.

| API                            | avg | 99% | max  | TPS    |    
|--------------------------------|-----|-----|------|--------|
| Regex API Thread Group         | 18  | 86  | 254  | 17784  | 
| Programmatic API Thread Group  | 13  | 67  | 169  | 19197  |  
| Hibernate API Thread Group     | 10  | 59  | 246  | 19960  | 


Conclusion

Before this test, I thought that my own code should perform way better than somebody else's code, but actually, Hibernate Validator was the best option for my test. 

You can also run this test and check the source code in my GitHub.

API Apache JMeter Hibernate Java (programming language) Strings

Opinions expressed by DZone contributors are their own.

Related

  • Express Hibernate Queries as Type-Safe Java Streams
  • Functional Approach To String Manipulation in Java
  • How to Automatically Detect Multiple Cybersecurity Threats from an Input Text String in Java
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook