Reputation: 870
i have a web api 2 project the client will request some data that is in a xml format. That XML will never change and i am wondering how i could keep it in ram so that it doesnt deserialize the xml each time it needs data from that file.
Would deserializing it at launch and then keep it in a static variable be the best way as it will only be use for reading ?
[HttpPost]
[Route("api/dosomething")]
public string DoSomething() {
var myData = XmlSerializer(MyDataStruct).Deserialize(something);
return myDate;
}
Here the xml is only used to communicate values to clients. How can i make it so that i could deserialize it once and then return that directly. Would using static member enable this feature ?
Upvotes: 2
Views: 4081
Reputation: 18265
A simple cache-aside approach with a static field could be a fair option:
private static MyDataStruct _myData;
[HttpPost]
[Route("api/dosomething")]
public string DoSomething() {
if(_myData == null)
{
_myData = new XmlSerializer(typeof(MyDataStruct)).Deserialize(something);
}
return _myData;
}
If you want even better performance and completely skip both the deserialization from your XML and the serialization of your response body into JSON/XML, then I strongly suggest you an HTTP output caching approach, using a library like this one: AspNetWebApi-OutputCache.
Upvotes: 2