Skip to content

Difference in codegen of string.IsNullOrEmpty() #63116

@ShreyasJejurkar

Description

@ShreyasJejurkar

I was playing with JIT a little bit recently, and found the below scenario where I am checking does give string is null or empty with two different styles,

  1. With raw null and length check.
  2. and with string.IsNullOrEmpty() built-in method, which does the same raw null and length check behind the scenes.

But the collagen is a little different for both cases!
For given a program below (corresponding sharplab link)

using System;
public class C {
    public void M() {
        var someString = "";
        
        if(someString == null || someString.Length == 0) {
            Console.Write("hello");
        }
    }
    
    public void T() {
        string someString = "";
        
        if(string.IsNullOrEmpty(someString)) {
            Console.Write("hello");
        }
    }
}

Following is the resulting codegen

C.M()
    L0000: push ebp
    L0001: mov ebp, esp
    L0003: mov ecx, [0x8d72018]
    L0009: cmp dword ptr [ecx+4], 0
    L000d: jne short L001a
    L000f: mov ecx, [0x8dce1d8]
    L0015: call System.Console.Write(System.String)
    L001a: pop ebp
    L001b: ret

C.T()
    L0000: mov ecx, [0x8dce1d8]
    L0006: call System.Console.Write(System.String)
    L000b: ret

As we can see above, codegen for string.IsNullOrEmpty(string) is quite optimized, so my question is can we do the same optimization for the raw null check call as well (OR maybe fold that raw call with the built-in method by the compiler), given the fact that the built-in also does the same behind the scenes, but still codegen is quite different!

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions