Hat ^ operator vs Math.Pow()

你说的曾经没有我的故事 提交于 2019-12-23 17:12:51

问题


Having perused the MSDN documentation for both the ^ (hat) operator and the Math.Pow() function, I see no explicit difference. Is there one?

There obviously is the difference that one is a function while the other is considered an operator, e.g. this will not work:

Public Const x As Double = 3
Public Const y As Double = Math.Pow(2, x) ' Fails because of const-ness

But this will:

Public Const x As Double = 3
Public Const y As Double = 2^x

But is there a difference in how they produce the end result? Does Math.Pow() do more safety checking for example? Or is one just some kind of alias for the other?


回答1:


One way to find out is to inspect the IL. For:

Dim x As Double = 3
Dim y As Double = Math.Pow(2, x)

The IL is:

IL_0000:  nop         
IL_0001:  ldc.r8      00 00 00 00 00 00 08 40 
IL_000A:  stloc.0     // x
IL_000B:  ldc.r8      00 00 00 00 00 00 00 40 
IL_0014:  ldloc.0     // x
IL_0015:  call        System.Math.Pow
IL_001A:  stloc.1     // y

And for:

Dim x As Double = 3
Dim y As Double = 2 ^ x

The IL also is:

IL_0000:  nop         
IL_0001:  ldc.r8      00 00 00 00 00 00 08 40 
IL_000A:  stloc.0     // x
IL_000B:  ldc.r8      00 00 00 00 00 00 00 40 
IL_0014:  ldloc.0     // x
IL_0015:  call        System.Math.Pow
IL_001A:  stloc.1     // y

IE the compiler has turned the ^ into a call to Math.Pow - they're identical at runtime.



来源:https://stackoverflow.com/questions/43804874/hat-operator-vs-math-pow

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