0

Returning json data through a web request lead us to make it lighter and faster. So I was wondering, what is better to return: a anonymous object or a DTO?

I've read some concerns about architecture: http://www.codeproject.com/Articles/1018716/Replacing-DTO-with-Anonymous-object and use of DTOs: Entity Framework is Too Slow. What are my options? But it's not my focus, I want to know what is lighter and faster on returning a web request.

Thanks!

Community
  • 1
  • 1
  • I wouldn't put a lot of weight in that CodeProject article. It's written by one guy and has no feedback. He doesn't really go into the downside, only shows how it _can_ be done. – D Stanley Mar 24 '16 at 14:57

1 Answers1

2

There should be no significant difference as far as "weight" or performance. Anonymous objects are classes just like DTOs, they just aren't defined at design-time, they are defined by the compiler.

The disadvangates of using anonymous types is that they are not type-safe outside of the method that defines it. It "works" when returning JSON because it uses reflection to get all of the properties of the type, just like a "normal" class.

The benefit of anonymous type is purely coding efficiency - you don't have to define a "type" for use within a single method. If, however, that type is going to be exposed by the method (whether directly or through JSON) then you should define a type for it.

D Stanley
  • 139,271
  • 11
  • 154
  • 219