Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...