当前位置:网站首页>Objectmapper, stop being new like a second product
Objectmapper, stop being new like a second product
2022-04-22 04:23:00 【Ashes collector】
Since the domestic light fastjson Frequent thunderstorms ,jackson json Is more and more widely used . In especial spring The family made it the default JSON Processing packages ,jackson The use of is developing explosively .
Many students found that ,jackson There is no parallel fastjson Of JSON.parseObjec In this way , It does look like a quick way . To parse json, You have to new One ObjectMapper, To handle the real parsing action .
It looks like this .
public String getCarString(Car car){
ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(car);
return str;
}
This code is in CV The engineer's hands were full of flowers .
magical .
Is there a problem with this code ?
You have to say it has a problem , It does perform correctly . You have to say it's okay , In the eyes of students pursuing performance , This must be a heinous piece of code .
General tools , It's all singletons , At the same time, it is thread safe .ObjectMapper No exception , It's also thread safe , You can execute it concurrently , There won't be any problems .
This code ,ObjectMapper Every time a method is called , Will generate a . In addition to causing a certain waste of memory of the younger generation , Is there any hard injury in the execution time ?
new And don't new, Is it really that different ?
There is a ,xjjdog Implicitly point out the problem of a piece of frequently called code , I was yelled by my little partner and took out the evidence .
evidence ? This has to be moved out Java Benchmarking tools in JMH, To find out .
JMH(the Java Microbenchmark Harness) It is such a tool that can do benchmarking . If you pass through our series of tools , Locate the hotspot code , To test its performance data , Evaluate improvements , You can give it to JMH. Its measurement accuracy is very high , Up to nanosecond level .
JMH It's a jar package , It is similar to the unit test framework JUnit It's very much like , You can make some basic configuration through annotations . Many of these configurations can be configured through main Methodical OptionsBuilder Set up .

The picture above is a typical one JMH Content of program execution . By starting multiple processes , Multiple threads , First perform warm-up , And then perform iterations , Finally, summarize all the test data for analysis . Before and after execution , Some pre and post operations can also be processed according to granularity .
JMH test result
To test the above scenario , We created the following benchmark classes . It is divided into three test scenarios :
-
Directly in the method new ObjectMapper
-
Share one globally ObjectMapper
-
Use ThreadLocal, One per thread ObjectMapper
Such a test belongs to cpu intensive . my cpu Yes 10 nucleus , It's directly distributed 10 Concurrency of threads ,cpu Run full during the test .
@BenchmarkMode({Mode.Throughput})
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@Threads(10)
public class ObjectMapperTest {
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@State(Scope.Benchmark)
public static class BenchmarkState {
ObjectMapper GLOBAL_MAP = new ObjectMapper();
ThreadLocal<ObjectMapper> GLOBAL_MAP_THREAD = new ThreadLocal<>();
}
@Benchmark
public Map globalTest(BenchmarkState state) throws Exception{
Map map = state.GLOBAL_MAP.readValue(json, Map.class);
return map;
}
@Benchmark
public Map globalTestThreadLocal(BenchmarkState state) throws Exception{
if(null == state.GLOBAL_MAP_THREAD.get()){
state.GLOBAL_MAP_THREAD.set(new ObjectMapper());
}
Map map = state.GLOBAL_MAP_THREAD.get().readValue(json, Map.class);
return map;
}
@Benchmark
public Map localTest() throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
Map map = objectMapper.readValue(json, Map.class);
return map;
}
public static void main(String[] args) throws Exception {
Options opts = new OptionsBuilder()
.include(ObjectMapperTest.class.getSimpleName())
.resultFormat(ResultFormatType.CSV)
.build();
new Runner(opts).run();
}
}
The test results are as follows .
Benchmark Mode Cnt Score Error Units
ObjectMapperTest.globalTest thrpt 5 25125094.559 ± 1754308.010 ops/s
ObjectMapperTest.globalTestThreadLocal thrpt 5 31780573.549 ± 7779240.155 ops/s
ObjectMapperTest.localTest thrpt 5 2131394.345 ± 216974.682 ops/s
As can be seen from the test results , If we call each time new One ObjectMapper, Can execute... Per second 200 Ten thousand times JSON analysis ; If the global uses one ObjectMapper, Then... Can be executed per second 2000 More than ten thousand times , It's fast enough 10 times .
If you use ThreadLocal The way , Each thread assigns it a parser , Then the performance will increase a little , But not to the point of exaggeration .
So when writing code in a project , We just need to ensure that there is a global ObjectMapper That's all right. .
Of course , because ObjectMapper There are many features to configure , You may be assigned a different scenario ObjectMapper. All in all , Its quantity doesn't need to be too much , Because it's thread safe .
So the conclusion is relatively clear , We only need to use one in the whole project ObjectMapper That's all right. , There's no need to be silly every time new One , After all, the performance is poor 10 times . If your JSON There are many custom configurations , Using global variables can highlight its advantages .
Don't think it's unnecessary , It's always good to keep good coding habits . High performance code is accumulated bit by bit . Short step , A thousand miles . Don't product the little stream , Beyond into the sea , That's the reason .
版权声明
本文为[Ashes collector]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220420399751.html
边栏推荐
- matplotlib画3dbox
- Mysql中的Decimal类型是什么?
- WebSocket学习
- How does IOT platform realize business configuration center
- Exploring Presto SQL Engine (2) - Analysis of join
- Data cleaning chapter05 | data grouping and data imbalance
- Revit (3) - second opening - create column
- DOM event flow and event delegation
- [recent force deduction] Fibonacci sequence + realizing queue with two stacks + printing linked list from end to end
- 腾讯 csig 面试简述(已通过)
猜你喜欢

PowerDesiPowerDesigner导入sql 不显示表关联关系 怎么解决

WebSocket学习

The core of improving data utilization efficiency in the transportation industry is to do a good job in data exchange and sharing

When the SQL statement is executed by hyperf, the parameter will have two single quotes

02-SparkSQL

如何在官网查看OracleJDK那个版本是否收费

NVIDIA, Wanxiang, fengyuzhu, dream chaser Fund... Talk about "new opportunities for yuan universe and industry" - 2022 yuan universe cloud Summit

Keras deep learning practice (2) -- using keras to construct neural network

05-Aggregation

Sequence traversal of binary tree
随机推荐
专家有料 | 张祖优:腾讯云DevSecOps实践与开源治理探索
Your mind will change your behavior, and your behavior will change your situation
OpenSCA版本升级 | OpenSCA v1.0.4版本发布
Summary of knowledge points of objects and classes
Experts have information | Zhang Zuyou: Tencent cloud devsecops practice and open source governance exploration
智慧用电安全管理系统
03-DataFrame & Column
Verify simple sorting using logarithm
Chapter 8 of C language programming (fifth edition of Tan Haoqiang) is good at using pointer exercises to analyze and answer
Web 安全之 XSS 攻击原理/分类/防御 详解
24 pictures to conquer border image
Insert a number into the ordered array (Bubble + rand function)
【openEuler】Failed to download metadata for repo ‘EPOL‘: Cannot d
Keras deep learning practice (2) -- using keras to construct neural network
sumo 教程——高速公路
How to solve the problem that the table association is not displayed when importing SQL from powerdesipowerdesigner
插一个数到排好序的数组中(冒泡+rand函数)
What is the decimal type in MySQL?
Mysql中的Decimal类型是什么?
二叉树的层序遍历