Is the Json.NET JsonSerializer threadsafe?

后端 未结 4 879
孤城傲影
孤城傲影 2021-01-07 16:29

I\'m trying to reduce the amount of garbage my web service generates, and I noticed that we\'re creating a new Json.NET JsonSerializer instance for each request

4条回答
  •  星月不相逢
    2021-01-07 16:56

    I noticed that we're creating a new Json.NET JsonSerializer instance for each request. It is not the most lightweight object ever...

    Maybe not "ever", but I suspect it's a very inexpensive object to create, because the library itself does this routinely, such as the static and oft-used JsonConvert.SerializeObject method, which is defined like this:

    public static string SerializeObject(object value, Type type, JsonSerializerSettings settings)
    {
        JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
    
        return SerializeObjectInternal(value, type, jsonSerializer);
    }
    

    Given the maturity and popularity of the library, I suspect that if JsonSerializer was even a little expensive to create, some effort would have been made to cache them in these static methods. So although it's thread safe, I still think that unless it's the most extreme of circumstances you're going to be fine creating them on demand.

提交回复
热议问题