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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

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

  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Handling “Element Is Not Clickable at Point” Exception in Selenium
  • A Comprehensive Guide To Building and Managing a White-Label Platform
  • Test Smells: Cleaning up Unit Tests
  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 user avatar
Fernando Boaglio
·
Jun. 03, 24 · Code Snippet
Like (1)
Save
Tweet
Share
6.6K Views

Join the DZone community and get the full member experience.

Join For Free

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

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: