Home > Software design >  why JsonElement is struct type?
why JsonElement is struct type?

Time:04-27

in many JSON parsers, the element of json is presented as object(reference) type.

However in C#, System.Text.Json JsonElement is struct type. Why JsonElement is struct type?

I'm worried about this could cause unnecessary memory copy.
What if JsonElement has very big data? what if JsonElement has array that contains over 1000 objects?

CodePudding user response:

If you look at the source code you'll see that JsonElement is very lightweight. It only has two fields: a reference to the containing document, and an index into the document. In particular, it doesn't directly contain all the data for the element.

This avoids creating a lot of memory churn, as it's efficient to (for example) iterate over all the elements in a document, without it having to create large numbers of objects.

  • Related