まずはこのコードを見てみてください。
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
for (int i = 0; i < 999999; i++) {
testclass aa = new testclass();
aa.method("XXXXX");
}
for (int i = 0; i < 999999; i++) {
testclass.smethod("XXXXX");
}
}
}
class testclass {
public string method(string val) {
return val.Trim();
}
public static string smethod(string val) {
return val.Trim();
}
}
}
なんてことはない処理をインスタンスメソッドで呼んだ場合と、スタティックメソッドで読んだ場合の違いを表しています。
特にTrim()を行う意味はありません。
このインスタンスを呼び出すときと、スタティックを呼び出すときのコスト差(うちのノートマシン調べ)はどれくらいあるでしょうか?
Visual Studioのパフォーマンス機能で調べた結果がコレです。
インスタンスメソッド |
ConsoleApplication1.testclass.method(string) |
300.211083 |
ConsoleApplication1.testclass..ctor() |
117.173502 |
System.Object..ctor() |
65.999618 |
合計 |
483.3842 |
スタティックメソッド |
ConsoleApplication1.testclass.smethod(string) |
128.153829 |
実に全体で3.7倍
直接呼び出すメソッドだけ比べても約2.3倍
.NETのBCL(ベースクラスライブラリ)を見ていてもわかるように、パラメータと戻り値だけですべてが語れるメソッドはstaticメソッドにするべきです。
コード分析機能を有効にしてもこの問題は指摘されます。
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VSENT.v80.ja/dv_vsetsa03/html/743f0af7-41d1-4852-8d97-af0688b31118.htm
http://msdn2.microsoft.com/ja-jp/library/ms245046.aspx
オブジェクト指向は決してパフォーマンス性向が良いとはいえません。
オブジェクト的に正しくないとかを振り回すだけでは融通が利かないだけでなく、パフォーマンス面で取り返しのつかない事態も想定できます。
#某ねっとみたいに・・・
当然DataSetなんかのように至れり尽くせりのものと、ミニマムプランで自作したクラスのパフォーマンスを比べたら10倍から開きがついてもおかしくはありません。
何事にも光と闇あり。
#Visual Studioのパフォーマンス計測ソフトはなかなかいいです。是非使ってみてください。