访问器方法中的空合并运算符 [英] null coalescing operator in accessor method

查看:107
本文介绍了访问器方法中的空合并运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在stackoverflow中四处查看,是否将空合并运算符放在访问器方法中是否会对性能产生影响.

i was looking around in stackoverflow whether putting null coalescing operators within an accessor method has any performance implications.

之前:

private Uri _Url;
public Uri Url
{
    if(_Url == null)
        _Url = new Uri(Utilities.GenerateUri());
    return _Url;
}

之后:

private Uri _Url;
public Uri Url 
{
    get 
    {
        return _Url = _Url ?? new Uri(Utilities.GenerateUri());
    }
}

我什至不确定语法是否正确,但是在调试时,将设置私有对象.

I'm not even sure if the syntax is correct, but when i debug, the private object is set.

在有人问这有什么意义之前,我们在内部进行辩论是为了提高可读性(对我来说第一个看起来更具可读性),还是为了提高性能而写.

Before anyone ask what's the point of doing it, we were debating internally whether to write for readability (the first looks more readable to me), or to write for performance.

我不知道编译器是否会优化?总是比手动进行null检查更好.微观优化不好,但是我很好奇

I don't know whether the compiler will optimize ?? better than a manual null check all the time. Micro-optimization is bad, but i am just curious

推荐答案

您实际上可以这样写:

return _Url ?? (_Url = new Uri(Utilities.GenerateUri()));

就性能而言,它实际上与使用if是相同的,所以没有区别.

As far as performance goes, it is practically the same thing as using if, so no difference.

这篇关于访问器方法中的空合并运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆