gpt4 book ai didi

jaxb - 如何提高 JAXB 性能?

转载 作者:行者123 更新时间:2023-12-01 06:56:31 25 4
gpt4 key购买 nike

这是我的转换代码。当我们处理大数据时,这需要很长时间......调用该方法几乎一百万次......我们可以清楚地看到它持有线程一段时间。

请建议我一些提高性能的方法!

public class GenericObjectXMLConverter<T> {

private T t = null;
private static JAXBContext jaxbContext =null;
public GenericObjectXMLConverter() {

}
public GenericObjectXMLConverter(T obj){
t = obj;
}

protected final Logger log = Logger.getLogger(getClass());

/**
* Converts the java Object and into a xml string message type.
* @param object the object to convert
* @return String the converted xml message as string
*/
public String objectToXMLMessage(T object) {
StringWriter stringWriter = new StringWriter();
//JAXBContext jaxbContext=null;
try {
jaxbContext = JAXBContext.newInstance(object.getClass());
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.marshal(object, stringWriter);
} catch (JAXBException e) {
log.warn("JAXBException occured while converting the java object into xml string :"+e.getMessage());
}
/*if(log.isDebugEnabled())
log.debug("xml string after conversion:"+stringWriter.toString());*/
return stringWriter.toString();
}

/**
* Converts a xml string message into a Java Object
* @param string the string message to convert
* @return Object the result as Java Object. If the message parameter is null then
* this method will simply return null.
*/
@SuppressWarnings("unchecked")
public T xmlToObject(String message) {
if(message.equals("") || message.equals(" ") || message.length()==0){
return null;
}else{
T object=null;
try {
jaxbContext = JAXBContext.newInstance(t.getClass());
StringReader reader = new StringReader(message);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
object = (T)jaxbUnmarshaller.unmarshal(reader);
} catch (JAXBException e) {
log.warn("JAXBException occured while converting the xml string into a Java Object :"+e.getMessage());
}
/* if(log.isDebugEnabled()){
log.debug("Java object after conversion:"+object.toString());
}*/
return object;
}
}

}

最佳答案

性能和 JAXB 运行时类

  • 您应该避免创建相同的 JAXBContext一遍又一遍。 JAXBContext是线程安全的,应该重用以提高性能。
  • Marshaller/Unmarshaller不是线程安全的,但可以快速创建。重用它们没什么大不了的。
  • 关于jaxb - 如何提高 JAXB 性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18607318/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com