Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

performance - Is *0.25 faster than / 4 in VB.NET

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...