Suppose a function in a web api queries a database, creates a new instance of a custom object, sets the properties of the custom object to the retrieved database data, converts the custom object to a json object and return it. My question is if the web api will be called thousands of time per minutes, would it be more efficient to not create the custom object and instead just create a json object and add each of the database data to it.
It depends.
If the custom object is simple then sure, just create the json object and move on.
But for a complex object (multi-level), the hassle of creating the json object would override the benefits of removing the custom object.
Since mysql is able to return a ready to go JSON string I would not use any code to create my return then doing one query on the database
Hi all, thanks for replying. My main concern is with the consumption of memory, if tens of thousands of requests are made to the web api per minute that means for each of the requests a new instance of the custom object is created and more memory is allocated for this. The real question is how fast can the garbage collector get rid of the mentioned object. I know we’re supposed to trust the efficiency of GC but I’m tempted to use System.GC.Collect() to force garbage collection on the object as soon as it is converted to a json object and no longer needed.
Are you anywhere near that level of activity? Sometimes you can overthink it and make things overly complicated.
It also goes back to my point on the custom objects complexity. It’s it’s something like
Then, yeah go ahead and create the json object and fill it.
But if it’s something like
- Personal Info
- FirstName
- MiddleName
- LastName
- EmailAddress
- Address
- Mailing Address
- Street Address
- City
- State
- Zip
- Billing Address
- Street Address
- City
- State
- Zip
- Mailing Address
- Order History
- Order 1
- Order number
- Order Date
- Order Total
- Item List
- Item 1
- Item 2
- Item 3
- Order 2
- Order number
- Order Date
- Order Total
- Item List
- Item 1
- Item 2
- Item 3
- Order 1
Then building that object directly to JSON may end up being slower, especially when dealing with direct entity objects where you instantiate the object, populate it, then convert it all at once..
"Great points! Memory consumption really does become a concern at high request volumes, especially when complex object models like the one you described are involved. It’s always a balance between clean architecture and performance. Sometimes directly constructing JSON makes sense for speed, but with deeply nested structures, the overhead can catch up quickly. Profiling and real-world testing at scale really help clarify the best path
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.