-5
using System.Collections.Generic;
using System.IO

Which variant is faster?

This?

List<short> a = new List<short>();
a.Add(0);
a.Add(1);
a.Add(2);
FileStream fs = new FileStream("file", FileMode.OpenOrCreate, FileAccess.Write){
    using ( BinaryWriter bw = new BinaryWriter(fs)){
        foreach ( short b in a ){
        bw.Write(b);
        }
    }
}

or this?

string a = "";
a += "0";
a += "1";
a += "2";
File.WriteAllText("file", a);

or this?

short[] a = new short[3];
a[0] = 0;
a[1] = 1;
a[2] = 2;
FileStream fs = new FileStream("file", FileMode.OpenOrCreate, FileAccess.Write){
using ( BinaryWriter bw = new BinaryWriter(fs)){
    foreach ( short b in a ){
        bw.Write(b);
    }
}

}

I would like to know how fast each of these pieces of code compiles, and and how can I measure the speed myself.

Jaroslav Tavgen
  • 312
  • 1
  • 9
  • 6
    [Which is faster?](https://ericlippert.com/2012/12/17/performance-rant/) – Peter Duniho Aug 25 '17 at 05:57
  • 2
    If you are interested in execution time then by using [StopWatch](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) you can measure that. – Amogh Aug 25 '17 at 06:00
  • 2
    Classes like a HashSet are documented to perform in O(1) time. This is documented on msdn. But normal methods like the ones you mention do not have such time specifications. You'll need to benchmark that yourself. Simply create the same scenario in all cases. Run the process for example 10000 times. Make sure to start a timer at the beginning and print out the time after 10000 repetitions. Then compare the time between the scenarios and repeat that 2 to 4 times to get rid of possible temporary performance issues. – Noel Widmer Aug 25 '17 at 06:01
  • 3
    *how fast each of these pieces of code **compiles*** - well, does it really matters how fast this code **compiles**? – Sir Rufo Aug 25 '17 at 06:02
  • first one is fast rather then second one....because its clear that short require less compile time then string so first case – Ajay Mistry Aug 25 '17 at 06:11
  • are you really asking about the compilation time? or the execution time? – Mong Zhu Aug 25 '17 at 06:22

1 Answers1

1

Don't try yourself to guess performance unless you know what happens under the hood. Instead, repeat your operation enough time that it needs some seconds to proceed, and measure each version with a Stopwatch. Try to do your benchmark separatively (not all test in the same benchmark), because compiler might alters your results if it detects it can use previous test results for next one.

Kinxil
  • 306
  • 2
  • 11