Is *0.25 faster than / 4 in VB.NET

我怕爱的太早我们不能终老 提交于 2019-12-14 03:22:52

问题


I know similar questions have been answered before but none of the answers I could find were specific to .NET.

Does the VB.NET compiler optimize expressions like:

x = y / 4

by compiling:

x = y * 0.25

And before anyone says don't worry the difference is small, i already know that but this will be executed a lot and choosing one over the other could make a useful difference in total execution time and will be much easier to do than a more major refactoring exercise.

Perhaps I should have mentioned for the benefit of those who live in an environment of total freedom: I am not at liberty to change to a different language. If I were I would probably have written this code in Fortran.


回答1:


As suggested here is a simple comparison:

Dim y = 1234.567
Dim x As Double

Dim c = 10000000000.0
Dim ds As Date
Dim df As Date
ds = Now
For i = 1 To c
  x = y / 4
Next
df = Now
Console.WriteLine("divide   " & (df - ds).ToString)
ds = Now
For i = 1 To c
  x = y * 0.25
Next
df = Now
Console.WriteLine("multiply " & (df - ds).ToString)

The output is:

divide   00:00:52.7452740
multiply 00:00:47.2607256

So divide does appear to be slower by about 10%. But this difference is so small that I suspected it to be accidental. Another two runs give:

divide   00:00:45.1280000
multiply 00:00:45.9540000

divide   00:00:45.9895985
multiply 00:00:46.8426838

Suggesting that in fact the optimization is made or that the arithmetic operations are a vanishingly small part of the total time.

In either case it means that I don't need to care which is used.

In fact ildasm shows that the IL uses div in the first loop and mul in the second. So it doesn't make the subsitution after all. Unless the JIT compiler does.



来源:https://stackoverflow.com/questions/20263050/is-0-25-faster-than-4-in-vb-net

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