Are there risks to optimizing code in C#?

2020-02-11 21:22发布

In the build settings panel of VS2010 Pro, there is a CheckBox with the label "optimize code"... of course, I want to check it... but being unusually cautious, I asked my brother about it and he said that it is unchecked for debugging and that in C++ it can potentially do things that would break or bug the code... but he doesn't know about C#.

So my question is, can I check this box for my release build without worrying about it breaking my code? Second, if it can break code, when and why? Links to explanations welcome.

The CheckBox I am talking about.

8条回答
We Are One
2楼-- · 2020-02-11 22:18

.net compiler optimization could cause bugs. happend to me today. took me a few hours to nail it. the code is:

for (int i = 0; i < list.Count-1; i++) {
  list[i+1].DoSomeThing();
  //some code
  if (someCondition) {
    list.insert(i+1, new Item());
    i++;
  }
}

at some point, the list[i+1] is addressed as list[i], as if both both point to the same item. this bug was so wierd. the code ran well at debug mode, and at release mode, but when I ran it out side visual studio, ex. from the .exe file, the code crashed. only turning off the compiler optimization fixed it.

查看更多
我只想做你的唯一
3楼-- · 2020-02-11 22:19

Should optimisations introduce bugs? No.

Could optimisations introduce bugs? Maybe, nothing's perfect after all.

Could optimsations uncover bugs that were always in your code, but are hidden when they are turned off? Absolutely, happens quite a bit.

The important thing is to realise that it's a change. Just like you'd test if you'd done a lot of changes, you should test when you turn them off. If final-release will have them turned on, then final-test must have them turned on too.

查看更多
登录 后发表回答