Hidden Boxing in the BCL?

老子叫甜甜 提交于 2019-12-11 02:28:07

问题


Recently I became aware that there are some parts in the BCL that still use some "legacy" code that was probably written before generics were introduced in v2.0 of the framework. Apparently, parts of that "legacy" code may cause the CLR to perform numerous boxing/unboxing operations.

Since excessive usage of boxing is never a good thing, I wanted to know whether there are some other, critical places in the BCL that you've noticed that boxing occur? Thanks


回答1:


Note that, for the specific example mentioned:

  • DateTime.Now calls a system function with considerably higher cost that the boxing of an int (even taking into account the increased gen0 collection frequency associated with it).
  • The precision of Dateime.Now is extremely low on windows platforms (10 -15 ms in most cases)
    • Thus calling this function a lot is not terribly useful anyway, if you are doing it then it is likely you're doing something else wrong...

As such you should only worry about the internals of this if your profiling indicates it is a problem.
Since MS never bothered to fix it it would seem unlikely that this has ever cropped up as a problem for any customers.

Of more concern to you in the hidden allocation vein is more likely to be:

  • Use of enumerations as keys in a dictionary (boxing occurs on every access).
  • Classes whose GetHashCode causes an allocation
  • Enumerator instances when using foreach on an IList<T> rather than List<T>

But again, all these (apart perhaps for the enumeration as key in dictionary which requires considerable effort to work around) should only be dealt with if you need to




回答2:


For one, you're right - it's not good. But burying down the dot net framework won't do you any good - you should accept framework internals as they are and hope for optimization in the future (for example, TransactionScope that have been optimized from 2.0 to 3.5 SP1).

Hope that cleared it up.




回答3:


Knowledge gives you power.

I recently found out how "path" + '\' + "fileName" is implemented.

The middle character '\' is boxed to an object first, then Concat(object, object, object) is called, then ToString is called three times, and then finally Concat(string, string, string) is called.

Had you the programmer know that, he/she could have written: "path" + "\" + "filename"



来源:https://stackoverflow.com/questions/1381370/hidden-boxing-in-the-bcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!