忍者ブログ
  C#   マクロ   Notepad++
04
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

単純に要素追加だけを考えた時に
インデクサとAddメソッドどちらが速いのか気になって気になった。

検証してみた。重複鍵とか一切考えずに検証してみた。



- 検証コード
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

class Class1 {
	static void Main() {
		int[] numbers = Enumerable.Range(1, 1000000).ToArray();
		
		Console.WriteLine("■Hashtable Addメソッド");
		Instrumentation(() => { AddHashTableMethod(numbers); });
		Console.WriteLine("■Hashtable インデクサ");
		Instrumentation(() => { AddHashTableIndexers(numbers); });
		Console.WriteLine("■Dictionary Addメソッド");
		Instrumentation(() => { AddDictionaryMethod(numbers); });
		Console.WriteLine("■Dictionary インデクサ");
		Instrumentation(() => { AddDictionaryIndexers(numbers); });
	}
	
	static void Instrumentation(Action action) {
		Stopwatch stopwatch = new Stopwatch();
		
		stopwatch.Start();
		action();
		stopwatch.Stop();
		
		Console.WriteLine(stopwatch.Elapsed);
	}
	
	static void AddHashTableMethod(params int[] numbers) {
		Hashtable hashtable = new Hashtable();
		foreach (int number in numbers) {
			hashtable.Add(number, number.ToString());
		}
	}
	
	static void AddHashTableIndexers(params int[] numbers) {
		Hashtable hashtable = new Hashtable();
		foreach (int number in numbers) {
			hashtable[number] = number.ToString();
		}
	}

	static void AddDictionaryMethod(params int[] numbers) {
		Dictionary<int, string> dictionary = new Dictionary<int, string>();
		foreach (int number in numbers) {
			dictionary.Add(number, number.ToString());
		}
	}
	
	static void AddDictionaryIndexers(params int[] numbers) {
		Dictionary<int, string> dictionary = new Dictionary<int, string>();
		foreach (int number in numbers) {
			dictionary[number] = number.ToString();
		}
	}
}

- 出力結果
■Hashtable Addメソッド
00:00:00.3471931
■Hashtable インデクサ
00:00:00.4032616
■Dictionary Addメソッド
00:00:00.3585081
■Dictionary インデクサ
00:00:00.3323293

の結果に。
32bitコンパイルでやってみたり、回数変えてみたりしてみたものの
速さ順位は変わりませんでした

DictionaryインデクサAddメソッドより
速いのはなんとなく理解できるとして
HashtableインデクサAddメソッドより遅いのはなんでじゃろう
なんとなくの予想ではボクシングによるキャスト回数が多いのかなと

何かわかれば追記の心構え
PR
この記事にコメントする
名前
URL
本文
パス   
PREV  HOME  NEXT
忍者ブログ  [PR]

(design by 山瀬)