Skip to content

Instantly share code, notes, and snippets.

@JasonBock
Last active June 18, 2019 13:02
Show Gist options
  • Save JasonBock/dea6707f5c2abe1997506506a2d5aca3 to your computer and use it in GitHub Desktop.
Save JasonBock/dea6707f5c2abe1997506506a2d5aca3 to your computer and use it in GitHub Desktop.
Benchmarking different ways to negate an integer in C#
// "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