Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
#1 #2 #3 avg(1,2,3) 生成込み?
struct-refarg 3845 3837 3840 3840.666667
struct 3975 3951 3947 3957.666667 *
out 3946 3945 3909 3933.333333
obj 4521 4754 4586 4620.333333 *
obj-arg 4431 4756 4658 4615
ary 4700 4847 4882 4809.666667 *
tuple 4672 5133 4921 4908.666667 *
stackalloc 4658 4671 4645 4658 *
ary-arg 4819 5254 5160 5077.666667
*/
unsafe void Main()
{
Test(() => func1()).Dump("1");
Test(() =>
{
double a, b, c;
func2(out a, out b, out c);
}).Dump("2");
Test(() => func3()).Dump("3");
Test(() =>
{
var xs = new double[3];
func4(xs);
}).Dump("4");
Test(() =>
{
var x = new Testobj();
func5(x);
}).Dump("5");
Test(() => func6()).Dump("6");
Test(() =>
{
var x = new TestobjS();
func10(ref x);
}).Dump("10");
Test(() => func11()).Dump("11");
Test(() =>
{
var xs = stackalloc int[3];
func12(xs);
}).Dump("12");
}
static long Test(Action f)
{
var sw = Stopwatch.StartNew();
for (var i = 0; i < 100000000; ++i) f();
sw.Stop();
return sw.ElapsedMilliseconds;
}
static Random rnd = new Random();
 
// ary: 配列を作って返す方法
static double[] func1()
{
    double a = rnd.Next();
    double b = rnd.Next();
    double c = rnd.Next();
 
    return new[] { a, b, c };
}
 
// out: outを使って返す方法
static void func2(out double a, out double b, out double c)
{
    a = rnd.Next();
    b = rnd.Next();
    c = rnd.Next();
}
 
// tuple: Tupleを使って返す方法
static Tuple<double,double,double> func3()
{
    double a = rnd.Next();
    double b = rnd.Next();
    double c = rnd.Next();
 
    return Tuple.Create(a, b, c);
}
// ary-arg: 受け取った配列に入れる方法
static void func4(double[] v)
{
    double a = rnd.Next();
    double b = rnd.Next();
    double c = rnd.Next();
 
    v[0] = a;
    v[1] = b;
    v[2] = c;
}
 
class Testobj
{
    public double a;
    public double b;
    public double c;
}
struct TestobjS
{
    public double a;
    public double b;
    public double c;
}
 
// obj-arg: 受け取ったオブジェクトに入れる方法
static void func5(Testobj o)
{
    o.a = rnd.Next();
    o.b = rnd.Next();
    o.c = rnd.Next();
}
 
// obj: オブジェクトを作って返す方法
static Testobj func6()
{
    return new Testobj()
    {
        a = rnd.Next(),
        b = rnd.Next(),
        c = rnd.Next()
    };
}
// ref-struct: 構造体を受ける
static void func10(ref TestobjS o)
{
    o.a = rnd.Next();
    o.b = rnd.Next();
    o.c = rnd.Next();
}
// struct: 構造体を返す
static TestobjS func11()
{
    return new TestobjS()
    {
        a = rnd.Next(),
        b = rnd.Next(),
        c = rnd.Next()
    };
}
// stackalloc: スタック上の配列を受ける
static unsafe void func12(int* xs)
{
xs[0] = rnd.Next();
xs[1] = rnd.Next();
xs[2] = rnd.Next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment