在 JIT/AOT 编译期间,CIL ldstr 是否被替换为对 string.Intern 的常量引用?

Is CIL ldstr replaced with constant reference to the string.Intern during JIT/AOT compilation?

假设我有一个代码需要优化但同时又易于调试。 因此,我会为我使用的每个值分配一个字符串。 该字符串是否会造成重大性能损失,或者它是否会变成在 JIT/AOT 编译期间从 string.Intern 获得的常量引用,从而变成一条简单的指令?

示例:

在 IL 中它将是 ldstr "gazilion lines"

是不是在JIT/AOT编译的时候变成了类似ldsflda string.InternCache.ID_0000647516166的东西 const string ID_0000647516166 = "gazilion lines"; 添加到 string.InternCache ?

是的,理论上我可以查看 https://github.com/mono/mono,但我不知道如何找到它。

是的,我正在混合使用 CIL、C# 和编译成的任何 CIL,但你明白了。

ldstr能保证是O(1)吗?

是的,它是 CLR 的 "implementation detail",但如果以这种方式优化它会很有意义。

Long answer: yes. Becomes a single MOV reg,imm instruction at runtime, be sure to use a debugger that can show you the disassembly so you don't have to fret about how the metadata token and the jitter works. – Hans Passant