Will my compiler ignore useless code?

前端 未结 9 1289
情深已故
情深已故 2021-02-06 21:53

I\'ve been through a few questions over the network about this subject but I didn\'t find any answer for my question, or it\'s for another language or it doesn\'t answer totally

9条回答
  •  深忆病人
    2021-02-06 22:24

    I've made a little form to test it according to a few answerers ideas about using long.MaxValue, here's my reference code:

    public Form1()
    {
        InitializeComponent();
        Stopwatch test = new Stopwatch();
        test.Start();
        myTextBox.Text = test.Elapsed.ToString();
    }
    

    and here's the code with kinda useless code:

    public Form1()
    {
        InitializeComponent();
        Stopwatch test = new Stopwatch();
        test.Start();
        for (int i = 0; i < int.MaxValue; i++)
        {
        }
        myTextBox.Text = test.Elapsed.ToString();
    }
    

    You'll remark that I used int.MaxValue instead of long.MaxValue, I didn't want to spend the year day on this one.

    As you can see:

    ---------------------------------------------------------------------
    |                   |   Debug               |   Release             |
    ---------------------------------------------------------------------
    |Ref                |   00:00:00.0000019    |   00:00:00.0000019    |
    |Useless code       |   00:00:05.3837568    |   00:00:05.2728447    |
    ---------------------------------------------------------------------
    

    The code isn't optimized. Hang on a bit, I'll try with some int[] to test int[].Lenght:

    public Form1()
    {
        InitializeComponent();
        int[] myTab = functionThatReturnInts(1);
    
        Stopwatch test = new Stopwatch();
        test.Start();
        for (int i = 0; i < myTab.Length; i++)
        {
    
        }
        myTextBox.Text = test.Elapsed.ToString();
    }
    public int[] functionThatReturnInts(int desiredSize)
    {
        return Enumerable.Repeat(42, desiredSize).ToArray();
    }
    

    And here's the results:

    ---------------------------------------------
    |   Size            |   Release             |
    ---------------------------------------------
    |             1     |   00:00:00.0000015    |
    |           100     |   00:00:00            |
    |        10 000     |   00:00:00.0000035    |
    |     1 000 000     |   00:00:00.0003236    |
    |   100 000 000     |   00:00:00.0312673    |
    ---------------------------------------------
    

    So even with arrays, it doesn't get optimized at all.

提交回复
热议问题