今天在寫spring boot時妒蛇,發(fā)現(xiàn)spring默認帶的轉json包為jackson润绵,而一般都大家都會引入fastjson來替換孝治。
引入fastjson的方式為进倍,首先引入alibaba的fastjson包,然后在啟動類中繼承WebMvcConfigurerAdapter 重寫 configureMessageConverters
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
//1定義轉換器 converter
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//配置fastjson
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.PrettyFormat);
//將fastjson 傳入轉換器
converter.setFastJsonConfig(config);
//將converter添加到converters當中
converters.add(converter);
}
為什么spring這么成熟的框架用的jackson而我們卻要改變?yōu)閒astjson呢螟左,難道fastjson真的就很fast啡浊?
我做了一個測試
//Spring 中默認用到的是Jackson 在框架搭建的時候一般都改用fastJson
public static void main(String [] str) {
Map map = new HashMap<String,Object>();
map = getMapData(map,1000000);
long fastJsonBegin = System.currentTimeMillis();
JSONObject fastJson = new JSONObject();
//fastJson
System.out.println("fastJson-------------------------------------------------");
// System.out.println("fastJson"+fastJson.toJSONString(map));
fastJson.toJSONString(map);
long fastJsonEnd = System.currentTimeMillis();
System.out.println("fastJson-------------time------------------------------------"+(fastJsonEnd-fastJsonBegin));
//jackson
long jacksonBegin = System.currentTimeMillis();
ObjectMapper jackson = new ObjectMapper();
try {
System.out.println("jackson-------------------------------------------------");
//System.out.println("jackson"+jackson.writeValueAsString(map));
jackson.writeValueAsString(map);
long jacksonEnd = System.currentTimeMillis();
System.out.println("jackson-------------time------------------------------------"+(jacksonEnd-jacksonBegin));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
public static Map getMapData(Map map,int count) {
for (int i = 0;i < count;i++) {
map.put("a"+i,i);
}
return map;
}
得到的運行結果
fastJson-------------------------------------------------
fastJson-------------time------------------------------------445
jackson-------------------------------------------------
jackson-------------time------------------------------------1123
果然是fastjson以快一倍的速度碾壓,于是我對上面的代碼進行了改動路狮,將獲取時間放在了創(chuàng)建fastjson及jackson的后面
//Spring 中默認用到的是Jackson 在框架搭建的時候一般都改用fastJson
public static void main(String [] str) {
Map map = new HashMap<String,Object>();
map = getMapData(map,1000000);
JSONObject fastJson = new JSONObject();
long fastJsonBegin = System.currentTimeMillis();
//fastJson
System.out.println("fastJson-------------------------------------------------");
// System.out.println("fastJson"+fastJson.toJSONString(map));
fastJson.toJSONString(map);
long fastJsonEnd = System.currentTimeMillis();
System.out.println("fastJson-------------time------------------------------------"+(fastJsonEnd-fastJsonBegin));
//jackson
ObjectMapper jackson = new ObjectMapper();
long jacksonBegin = System.currentTimeMillis();
try {
System.out.println("jackson-------------------------------------------------");
//System.out.println("jackson"+jackson.writeValueAsString(map));
jackson.writeValueAsString(map);
long jacksonEnd = System.currentTimeMillis();
System.out.println("jackson-------------time------------------------------------"+(jacksonEnd-jacksonBegin));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
結果為
fastJson-------------------------------------------------
fastJson-------------time------------------------------------385
jackson-------------------------------------------------
jackson-------------time------------------------------------309
很明顯jackson的速度優(yōu)于fastjson虫啥,只是蔚约,在創(chuàng)建對象時fastjson比jactson快
我們看一下兩個的構造方法
fastjson
private static final long serialVersionUID = 1L;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private final Map<String, Object> map;
public JSONObject(){
this(DEFAULT_INITIAL_CAPACITY, false);
}
public JSONObject(int initialCapacity, boolean ordered){
if (ordered) {
map = new LinkedHashMap<String, Object>(initialCapacity);
} else {
map = new HashMap<String, Object>(initialCapacity);
}
}
jackson
public ObjectMapper() {
this(null, null, null);
}
public ObjectMapper(JsonFactory jf,
DefaultSerializerProvider sp, DefaultDeserializationContext dc)
{
/* 02-Mar-2009, tatu: Important: we MUST default to using
* the mapping factory, otherwise tree serialization will
* have problems with POJONodes.
* 03-Jan-2010, tatu: and obviously we also must pass 'this',
* to create actual linking.
*/
if (jf == null) {
_jsonFactory = new MappingJsonFactory(this);
} else {
_jsonFactory = jf;
if (jf.getCodec() == null) { // as per [JACKSON-741]
_jsonFactory.setCodec(this);
}
}
_subtypeResolver = new StdSubtypeResolver();
RootNameLookup rootNames = new RootNameLookup();
// and default type factory is shared one
_typeFactory = TypeFactory.defaultInstance();
SimpleMixInResolver mixins = new SimpleMixInResolver(null);
_mixIns = mixins;
BaseSettings base = DEFAULT_BASE.withClassIntrospector(defaultClassIntrospector());
_configOverrides = new ConfigOverrides();
_serializationConfig = new SerializationConfig(base,
_subtypeResolver, mixins, rootNames, _configOverrides);
_deserializationConfig = new DeserializationConfig(base,
_subtypeResolver, mixins, rootNames, _configOverrides);
// Some overrides we may need
final boolean needOrder = _jsonFactory.requiresPropertyOrdering();
if (needOrder ^ _serializationConfig.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)) {
configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, needOrder);
}
_serializerProvider = (sp == null) ? new DefaultSerializerProvider.Impl() : sp;
_deserializationContext = (dc == null) ?
new DefaultDeserializationContext.Impl(BeanDeserializerFactory.instance) : dc;
// Default serializer factory is stateless, can just assign
_serializerFactory = BeanSerializerFactory.instance;
}
這樣就一目了然的看到了耗時的原因