Value vs Reference: A Performance Test

I have recently started to learned about classes and objects in C♯. In one of my lectures, Rob Miles mentioned that passing by reference introduced a slight performance hit, and I decided to test this.

Here is the code I used:

using System;
using System.Diagnostics;

class ValueVsReference
    public static void SetValue(int somenumber, int maxi)
        for (int i = 0; i < maxi; i++)
            somenumber = i;

    public static void SetReference(ref int somenumber, int maxi)
        for(int i = 0; i < maxi; i++)
            somenumber = i;

    public static void Main()
        int iterations = 100000;
        int a = 0;
        Console.Write("Iterations: {0} ", iterations);

        Console.Write("Value: ");
        Stopwatch valuetime = new Stopwatch();
        SetValue(a, iterations);
        Console.Write("{0} ", valuetime.Elapsed);

        Console.Write("Reference: ");
        Stopwatch referencetime = new Stopwatch();
        SetReference(ref a, iterations);


The results for 10,000 iterations can be found in this pastebin.

Average times:

Final result: References are indeed slower than values, by ~5% (100 - ((0.00009295/0.0000885)*100)). Normally you would not need to worry about this performance drop though since it is so small.

Tag Cloud

3d 3d printing account algorithms android announcement architecture archives arduino artificial intelligence artix assembly async audio automation backups bash batch blog bookmarklet booting bug hunting c sharp c++ challenge chrome os code codepen coding conundrums coding conundrums evolved command line compilers compiling compression css dailyprogrammer data analysis debugging demystification distributed computing documentation downtime electronics email embedded systems encryption es6 features ethics event experiment external first impressions future game github github gist gitlab graphics hardware hardware meetup holiday holidays html html5 html5 canvas infrastructure interfaces internet interoperability io.js jabber jam javascript js bin labs learning library linux lora low level lua maintenance manjaro network networking nibriboard node.js operating systems performance photos php pixelbot portable privacy problem solving programming problems project projects prolog protocol protocols pseudo 3d python reddit redis reference releases resource review rust searching secrets security series list server software sorting source code control statistics storage svg talks technical terminal textures thoughts three thing game three.js tool tutorial twitter ubuntu university update updates upgrade version control virtual reality virtualisation visual web website windows windows 10 xmpp xslt


Art by Mythdael