Last active
June 18, 2019 13:02
-
-
Save JasonBock/dea6707f5c2abe1997506506a2d5aca3 to your computer and use it in GitHub Desktop.
Benchmarking different ways to negate an integer in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "Inspired" by https://twitter.com/shit_sharp/status/1004360358306467844 | |
using BenchmarkDotNet.Attributes; | |
using System; | |
namespace NegativeBenchmark | |
{ | |
[MemoryDiagnoser] | |
public class NegatingNumbers | |
{ | |
private readonly int value = new Random().Next(); | |
[Benchmark] | |
public int NegateWithNegation() => -this.value; | |
[Benchmark] | |
public int NegateWithNegativeOne() => this.value * -1; | |
[Benchmark] | |
public int NegateWithString() => Int32.Parse("-" + this.value.ToString()); | |
} | |
class Program | |
{ | |
static void Main() => BenchmarkRunner.Run<NegatingNumbers>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment