Skip to content

Use null-coalescing assignment where applicable#294

Merged
slozier merged 3 commits intoIronLanguages:mainfrom
BCSharp:null_coal
Feb 24, 2026
Merged

Use null-coalescing assignment where applicable#294
slozier merged 3 commits intoIronLanguages:mainfrom
BCSharp:null_coal

Conversation

@BCSharp
Copy link
Member

@BCSharp BCSharp commented Feb 23, 2026

This is for both performance and readability improvements.

_alias = "$lambda" + ++_lambdaId;
}
}
_alias ??= lambda.Name;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this is adding an extra null check so not quite equivalent. Was this intentional?

Copy link
Member Author

@BCSharp BCSharp Feb 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for paying attention 😄 (there are a lot of changes), but yes, it was intentional, for readability.

I also thought it would be better performance-wise, but after closer examination of the generated IL code it turns out that the performance is better in Debug (unoptimized) configuration but worse in Release (optimized).

So I will fix it in the next commit.

Here is some background info. Considering the code path when _alias is already not null.

if (_alias == null) {
    _alias = lambda.Name;
    _alias ??= "$lambda" + ++_lambdaId;
}

generates normally

IL_0001	ldarg.0	
IL_0002	ldnull	
IL_0003	ceq	
IL_0005	stloc.0	
IL_0006	ldloc.0	
IL_0007	brfalse.s	IL_0039
...
IL_0039	ret	

But when optimized:

IL_0000	ldarg.0	
IL_0001	brtrue.s	IL_0031
...
IL_0031	ret	

Code:

_alias ??= lambda.Name;
_alias ??= "$lambda" + ++_lambdaId;

generates in both release and debug:

IL_0001	ldarg.0	
IL_0002	brtrue.s	IL_000C
...
IL_000C	ldarg.0	
IL_000D	brtrue.s	IL_0032
...
IL_0032	ret	

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option that wins in both Debug and Release:

_alias ??= lambda.Name ?? "$lambda" + ++_lambdaId;

Copy link
Contributor

@slozier slozier left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@slozier slozier merged commit 8a967cf into IronLanguages:main Feb 24, 2026
8 checks passed
@BCSharp BCSharp deleted the null_coal branch February 24, 2026 03:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants