为什么BitConverter比直接进行按位运算要慢? [英] Why is BitConverter slower than doing the bitwise operations directly?

查看:74
本文介绍了为什么BitConverter比直接进行按位运算要慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近对一些代码进行了分析,发现最大的CPU使用率正在通过调用BitConverter来消耗,例如:

I recently did some profiling on some code and found that the largest CPU usage was being consumed by calls to BitConverter such as:

return BitConverter.ToInt16(new byte[] { byte1, byte2 });

切换至类似内容时

return (short)(byte1 << 8 | byte2);

我注意到性能有了很大提高.

I noticed a huge improvement in performance.

我的问题是,为什么使用BitConverter这么慢?我本来以为BitConverter本质上是在内部进行相同类型的位移位.

My question is why is using BitConverter so much slower? I would have assumed that BitConverter was essentially doing the same kind of bit shifting internally.

推荐答案

BitConverter 的调用涉及到新对象的分配和初始化.然后一个方法调用.在方法调用内部是参数验证.

The call to BitConverter involves the allocation and initialisation of a new object. And then a method call. And inside the method call is parameter validation.

按位运算可以直接编译为少数几个CPU操作码,以进行后跟or的移位.

The bitwise operations can be compiled right down to a handful of CPU opcodes to do a shift followed by the or.

后者肯定会更快,因为它消除了前者的所有开销.

The latter will surely be faster because it removes all of the overhead of the former.

这篇关于为什么BitConverter比直接进行按位运算要慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆