Performance Comparison of Java Constructors, Setters, and Builder Pattern
The article examines Java performance optimization by profiling constructor initialization, individual setter calls, and Lombok's builder pattern, showing that direct constructor usage consistently outperforms setters and builders, and provides practical coding tips for faster Java applications.
When optimizing Java code, the author uses JProfiler to identify time‑consuming sections and proposes several efficiency tips, such as preferring constructors over multiple setter calls, using arrays instead of lists, writing index‑based loops with cached lengths, reusing variables, employing inner classes, and selecting the appropriate JSON library after testing.
The following test compares the execution time of object creation via a constructor versus a series of setter calls:
package com.lxk.fast;
import com.google.common.collect.Lists;
import com.lxk.model.Car;
import com.lxk.model.Dog;
/**
* Test which is faster: direct construction or using setters.
*/
public class FastIsConstructOrSet {
public static void main(String[] args) {
testFast();
}
/** Use JProfiler to see time proportion */
private static void testFast() {
while (true) {
//27.4%
set();
//72.6%
construct();
}
}
/** Constructor assigns values */
private static void construct() {
Car car = new Car("oooo", 100, Lists.newArrayList(new Dog("aaa", true, true)));
}
/** Setters assign values */
private static void set() {
Car car = new Car();
car.setSign("oooo");
car.setPrice(100);
Dog dog = new Dog();
dog.setName("aaa");
dog.setAlive(true);
dog.setLoyal(true);
car.setMyDog(Lists.newArrayList(dog));
}
}The profiling results show that the constructor approach is significantly faster, confirming that when all properties can be set at once, using a constructor is preferable.
Curious about the builder pattern, the author adds a Lombok‑based builder test:
@Test
public void testFast2() {
while (true) {
//33%
set();
//12.4%
construct();
//54.6%
builder();
}
}
private static void builder() {
Car car = Car.builder()
.sign("0000")
.price(100)
.myDog(Lists.newArrayList(Dog.builder().name("aaa").alive(true).isLoyal(true).build()))
.build();
}Even with the builder, the constructor remains the fastest; the observed time ratios stay consistent (approximately 2.64 : 1 in favor of constructors). The article concludes that direct constructor initialization is the most efficient way to set object properties in Java.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.