govert / RobustGeometry.NET

A computational geometry library for .NET.
Other
90 stars 16 forks source link

advise: add "NoOptimization" flag #2

Open HenryHo2006 opened 8 years ago

HenryHo2006 commented 8 years ago

some unit test code like var result = a + b - a, it will be fault in release mode, add [MethodImpl(MethodImplOptions.NoOptimization)] to avoid fault.

govert commented 8 years ago

Are you sure about this? I would expect the compiler to never simplify a+b-a to b, since the semantics would change. Could you help me reproduce the difference?

I could get no difference with and without the NoOptimization using this code (in both cases I get infinity - as I'd expect):

using System;
using System.Runtime.CompilerServices;

namespace TestFloatOptimization
{
    class Program
    {
        static void Main(string[] args)
        {
            double a = double.MaxValue;
            double b = double.MaxValue;
            double withOpt = WithOpt(a, b);
            double noOpt = NoOpt(a, b);

            Console.WriteLine("WithOpt: " + withOpt.ToString("R"));
            Console.WriteLine("NoOpt:   " + noOpt.ToString("R"));
            Console.ReadLine();
        }

        static double WithOpt(double a, double b)
        {
            return a+b-a;
        }

        [MethodImpl(MethodImplOptions.NoOptimization)]
        static double NoOpt(double a, double b)
        {
            return a+b-a;
        }
    }
}