Prestasi Kerangka Pemetaan Java

1. Pengenalan

Untuk membuat aplikasi Java besar yang terdiri daripada beberapa lapisan memerlukan penggunaan beberapa model seperti model ketekunan, model domain atau apa yang disebut DTO. Menggunakan pelbagai model untuk lapisan aplikasi yang berbeza memerlukan kita menyediakan cara pemetaan antara kacang.

Melakukannya secara manual dapat dengan cepat membuat banyak kod plat boiler dan memakan banyak masa. Nasib baik bagi kami, terdapat beberapa kerangka pemetaan objek untuk Java.

Dalam tutorial ini, kita akan membandingkan prestasi kerangka pemetaan Java yang paling popular.

2. Rangka Kerja Pemetaan

2.1. Dozer

Dozer adalah kerangka pemetaan yang menggunakan rekursi untuk menyalin data dari satu objek ke objek lain . Rangka kerja ini bukan hanya dapat menyalin sifat antara kacang, tetapi juga dapat menukar antara jenis secara automatik.

Untuk menggunakan kerangka Dozer, kita perlu menambahkan kebergantungan pada projek kita:

 com.github.dozermapper dozer-core 6.5.0 

Maklumat lebih lanjut mengenai penggunaan rangka Dozer boleh didapati dalam artikel ini.

Dokumentasi kerangka boleh didapati di sini.

2.2. Orika

Orika adalah kerangka pemetaan kacang ke kacang yang secara berulang-ulang menyalin data dari satu objek ke objek lain .

Prinsip umum kerja Orika serupa dengan Dozer. Perbezaan utama antara keduanya adalah hakikat bahawa Orika menggunakan generasi bytecode . Ini memungkinkan untuk menghasilkan pemetaan lebih cepat dengan overhead minimum.

Untuk menggunakannya,kita perlu menambahkan kebergantungan pada projek kita:

 ma.glasnost.orika orika-core 1.5.4 

Maklumat lebih terperinci mengenai penggunaan Orika boleh didapati dalam artikel ini.

Dokumentasi sebenar kerangka boleh didapati di sini.

2.3. Struktur Peta

MapStruct adalah penjana kod yang menghasilkan kelas pemetik kacang secara automatik.

MapStruct juga mempunyai kemampuan untuk menukar antara pelbagai jenis data. Maklumat lebih lanjut mengenai cara menggunakannya boleh didapati dalam artikel ini.

Untuk menambah MapStructuntuk projek kami, kami perlu memasukkan kebergantungan berikut:

 org.mapstruct mapstruct 1.3.1.Final 

Dokumentasi kerangka boleh didapati di sini.

2.4. ModelMapper

ModelMapper adalah kerangka yang bertujuan untuk mempermudah pemetaan objek, dengan menentukan bagaimana objek memetakan satu sama lain berdasarkan konvensi. Ia menyediakan API selamat jenis dan refactoring-safe.

Lebih banyak maklumat mengenai rangka boleh didapati dalam dokumentasi.

Untuk memasukkan ModelMapper dalam projek kami, kami perlu menambahkan kebergantungan berikut:

 org.modelmapper modelmapper 2.3.8 

2.5. JMapper

JMapper adalah kerangka pemetaan yang bertujuan untuk menyediakan pemetaan berprestasi tinggi yang mudah digunakan antara Java Beans.

Kerangka ini bertujuan untuk menerapkan prinsip DRY menggunakan Anotasi dan pemetaan hubungan.

Rangka kerja ini membolehkan pelbagai cara konfigurasi: berasaskan anotasi, XML atau API.

Maklumat lebih lanjut mengenai rangka kerja boleh didapati dalam dokumentasinya.

Untuk memasukkan JMapper dalam projek kami, kami perlu menambahkan kebergantungannya:

 com.googlecode.jmapper-framework jmapper-core 1.6.1.CR2 

3. Model Pengujian

Untuk dapat menguji pemetaan dengan betul, kita harus memiliki model sumber dan sasaran. Kami telah membuat dua model ujian.

First one is just a simple POJO with one String field, this allowed us to compare frameworks in simpler cases and check whether anything changes if we use more complicated beans.

The simple source model looks like below:

public class SourceCode { String code; // getter and setter }

And its destination is quite similar:

public class DestinationCode { String code; // getter and setter }

The real-life example of source bean looks like that:

public class SourceOrder { private String orderFinishDate; private PaymentType paymentType; private Discount discount; private DeliveryData deliveryData; private User orderingUser; private List orderedProducts; private Shop offeringShop; private int orderId; private OrderStatus status; private LocalDate orderDate; // standard getters and setters }

And the target class looks like below:

public class Order { private User orderingUser; private List orderedProducts; private OrderStatus orderStatus; private LocalDate orderDate; private LocalDate orderFinishDate; private PaymentType paymentType; private Discount discount; private int shopId; private DeliveryData deliveryData; private Shop offeringShop; // standard getters and setters }

The whole model structure can be found here.

4. Converters

To simplify the design of the testing setup, we've created the Converter interface:

public interface Converter { Order convert(SourceOrder sourceOrder); DestinationCode convert(SourceCode sourceCode); }

And all our custom mappers will implement this interface.

4.1. OrikaConverter

Orika allows for full API implementation, this greatly simplifies the creation of the mapper:

public class OrikaConverter implements Converter{ private MapperFacade mapperFacade; public OrikaConverter() { MapperFactory mapperFactory = new DefaultMapperFactory .Builder().build(); mapperFactory.classMap(Order.class, SourceOrder.class) .field("orderStatus", "status").byDefault().register(); mapperFacade = mapperFactory.getMapperFacade(); } @Override public Order convert(SourceOrder sourceOrder) { return mapperFacade.map(sourceOrder, Order.class); } @Override public DestinationCode convert(SourceCode sourceCode) { return mapperFacade.map(sourceCode, DestinationCode.class); } }

4.2. DozerConverter

Dozer requires XML mapping file, with the following sections:

  com.baeldung.performancetests.model.source.SourceOrder com.baeldung.performancetests.model.destination.Order  status orderStatus    com.baeldung.performancetests.model.source.SourceCode com.baeldung.performancetests.model.destination.DestinationCode  

After defining the XML mapping, we can use it from code:

public class DozerConverter implements Converter { private final Mapper mapper; public DozerConverter() { this.mapper = DozerBeanMapperBuilder.create() .withMappingFiles("dozer-mapping.xml") .build(); } @Override public Order convert(SourceOrder sourceOrder) { return mapper.map(sourceOrder,Order.class); } @Override public DestinationCode convert(SourceCode sourceCode) { return mapper.map(sourceCode, DestinationCode.class); } }

4.3. MapStructConverter

MapStruct definition is quite simple as it's entirely based on code generation:

@Mapper public interface MapStructConverter extends Converter { MapStructConverter MAPPER = Mappers.getMapper(MapStructConverter.class); @Mapping(source = "status", target = "orderStatus") @Override Order convert(SourceOrder sourceOrder); @Override DestinationCode convert(SourceCode sourceCode); }

4.4. JMapperConverter

JMapperConverter requires more work to do. After implementing the interface:

public class JMapperConverter implements Converter { JMapper realLifeMapper; JMapper simpleMapper; public JMapperConverter() { JMapperAPI api = new JMapperAPI() .add(JMapperAPI.mappedClass(Order.class)); realLifeMapper = new JMapper(Order.class, SourceOrder.class, api); JMapperAPI simpleApi = new JMapperAPI() .add(JMapperAPI.mappedClass(DestinationCode.class)); simpleMapper = new JMapper( DestinationCode.class, SourceCode.class, simpleApi); } @Override public Order convert(SourceOrder sourceOrder) { return (Order) realLifeMapper.getDestination(sourceOrder); } @Override public DestinationCode convert(SourceCode sourceCode) { return (DestinationCode) simpleMapper.getDestination(sourceCode); } }

We also need to add @JMap annotations to each field of the target class. Also, JMapper can't convert between enum types on its own and it requires us to create custom mapping functions :

@JMapConversion(from = "paymentType", to = "paymentType") public PaymentType conversion(com.baeldung.performancetests.model.source.PaymentType type) { PaymentType paymentType = null; switch(type) { case CARD: paymentType = PaymentType.CARD; break; case CASH: paymentType = PaymentType.CASH; break; case TRANSFER: paymentType = PaymentType.TRANSFER; break; } return paymentType; }

4.5. ModelMapperConverter

ModelMapperConverter requires us to only provide the classes that we want to map:

public class ModelMapperConverter implements Converter { private ModelMapper modelMapper; public ModelMapperConverter() { modelMapper = new ModelMapper(); } @Override public Order convert(SourceOrder sourceOrder) { return modelMapper.map(sourceOrder, Order.class); } @Override public DestinationCode convert(SourceCode sourceCode) { return modelMapper.map(sourceCode, DestinationCode.class); } }

5. Simple Model Testing

For the performance testing, we can use Java Microbenchmark Harness, more information about how to use it can be found in this article.

We've created a separate benchmark for each Converter with specifying BenchmarkMode to Mode.All.

5.1. AverageTime

JMH returned the following results for average running time (the lesser the better) :

Framework Name Average running time (in ms per operation)
MapStruct 10 -5
JMapper 10 -5
Orika 0.001
ModelMapper 0.001
Dozer 0.002

This benchmark shows clearly that both MapStruct and JMapper have the best average working times.

5.2. Throughput

In this mode, the benchmark returns the number of operations per second. We have received the following results (more is better) :

Framework Name Throughput (in operations per ms)
MapStruct 133719
JMapper 106978
Orika 1800
ModelMapper 978
Dozer 471

In throughput mode, MapStruct was the fastest of the tested frameworks, with JMapper a close second.

5.3. SingleShotTime

This mode allows measuring the time of single operation from it's beginning to the end. The benchmark gave the following result (less is better):

Framework Name Single Shot Time (in ms per operation)
JMapper 0.015
MapStruct 0.450
Dozer 2.094
Orika 2.898
ModelMapper 4.837

Here, we see that JMapper returns better result than MapStruct.

5.4. SampleTime

This mode allows sampling of the time of each operation. The results for three different percentiles look like below:

Sample Time (in milliseconds per operation)
Framework Name p0.90 p0.999 p1.0
JMapper 10-4 0.001 2.6
MapStruct 10-4 0.001 3
Orika 0.001 0.010 4
ModelMapper 0.002 0.015 3.2
Dozer 0.003 0.021 25

All benchmarks have shown that MapStruct and JMapper are both good choices depending on the scenario.

6. Real-Life Model Testing

For the performance testing, we can use Java Microbenchmark Harness, more information about how to use it can be found in this article.

We have created a separate benchmark for each Converter with specifying BenchmarkMode to Mode.All.

6.1. AverageTime

JMH returned the following results for average running time (less is better) :

Framework Name Average running time (in ms per operation)
MapStruct 10 -4
JMapper 10 -4
Orika 0.004
ModelMapper 0.059
Dozer 0.103

6.2. Throughput

In this mode, the benchmark returns the number of operations per second. For each of the mappers we've received the following results (more is better) :

Framework Name Throughput (in operations per ms)
JMapper 7691
MapStruct 7120
Orika 281
ModelMapper 19
Dozer 10

6.3. SingleShotTime

This mode allows measuring the time of single operation from it's beginning to the end. The benchmark gave the following results (less is better):

Framework Name Single Shot Time (in ms per operation)
JMapper 0.253
MapStruct 0.532
Dozer 9.495
ModelMapper 16.288
Orika 18.081

6.4. SampleTime

This mode allows sampling of the time of each operation. Sampling results are split into percentiles, we'll present results for three different percentiles p0.90, p0.999, and p1.00:

Sample Time (in milliseconds per operation)
Framework Name p0.90 p0.999 p1.0
JMapper 10-3 0.008 64
MapStruct 10-3 0.010 68
Orika 0.006 0.278 32
ModelMapper 0.083 2.398 97
Dozer 0.146 4.526 118

While the exact results of the simple example and the real-life example were clearly different, but they do follow more or less the same trend. In both examples, we saw a close contest between JMapper and MapStruct for the top spot.

6.5. Conclusion

Based on the real-life model testing we performed in this section, we can see that the best performance clearly belongs to JMapper, although MapStruct is a close second. In the same tests, we see that Dozer is consistently at the bottom of our results table, except for SingleShotTime.

7. Summary

In this article, we've conducted performance tests of five popular Java bean mapping frameworks: ModelMapper, MapStruct, Orika, Dozer, and JMapper.

Seperti biasa, sampel kod boleh didapati di GitHub.