Is the use of ??
to update a value only when a new value exists equivalent to the use of a conditional, or is it less efficient?
I.e. in bar.Foo = qux.Foo ?? bar.Foo
, when qux.Foo == null
and the value defaults to bar.Foo
, is that interpreted as a "do nothing", or as "read bar.Foo
-> write to bar.Foo
"?
Long version:
I have a PATCH endpoint. When the front end sends the JSON data, each property is updated if, and only if, it is not null. Let's call the current object bar
, the received DTO qux
and the relevant property Foo
.
I believe this is the "regular" way of doing it:
if (qux.Foo != null)
{
bar.Foo = qux.Foo;
}
However, I have a personal preference for the use of ?? here.
bar.Foo = qux.Foo ?? bar.Foo
It just looks prettier.
Now, something that occurred to me is that my code might be performing an unnecessary read and an unnecessary write, which could be pretty bad given that we work with base64 conversion so some props can get as large as several MBs.
The truth is I have no idea how to go about measuring this by myself, and couldn't find an answer anywhere.
Yes it will perform a write. The reason (other than the fact that you explicitly coded it that way) is because your property might have a setter that would not be called if the seemingly pointless write were optimized away.
As mentioned in the comments, there should be no performance concern because you are just copying a reference to an object, not the object itself. It might be different if you were using a struct
that copies by value, but even in that case the "regular" way of doing it would be perfectly fine.
In fact I would not even fault you for inlining the if
in this case:
if (qux.Foo != null) bar.Foo = qux.Foo;