Created
June 30, 2014 00:49
-
-
Save mntone/ee0fb34bb3fa9c3567e0 to your computer and use it in GitHub Desktop.
IndexOf いろいろ比較。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace StringIndexOfSpeedTest | |
{ | |
class Program | |
{ | |
static void Main( string[] args ) | |
{ | |
var data = "bbbbbbbbbbbbbbbbbbbbbbbbbbb[bbbbbbbbbbbbbbbbbbbbbbbbbbb"; | |
var find = '['; | |
var count = 10000000; | |
var io1 = GetTime( DefaultIndexOf, count, data, find ); | |
var io2 = GetTime( IndexOfIndexer, count, data, find ); | |
var io3 = GetTime( IndexOfPointer, count, data, find ); | |
Console.WriteLine( "DefaultIndexOf:\t{0}", io1 ); | |
Console.WriteLine( "IndexOfIndexer:\t{0}", io2 ); | |
Console.WriteLine( "IndexOfPointer:\t{0}", io3 ); | |
Console.ReadKey( true ); | |
} | |
static TimeSpan GetTime( Func<string, char, int> ex, int count, string data, char find ) | |
{ | |
var start = DateTime.Now; | |
var c = 0; | |
while( c++ < count ) | |
{ | |
ex( data, find ); | |
} | |
var end = DateTime.Now; | |
return end - start; | |
} | |
static int DefaultIndexOf( string data, char find ) | |
{ | |
return data.IndexOf( find ); | |
} | |
static int IndexOfIndexer( string data, char find ) | |
{ | |
var dataLength = data.Length; | |
int pos = 0; | |
while( pos < dataLength ) | |
{ | |
if( data[pos] == find ) | |
{ | |
break; | |
} | |
++pos; | |
} | |
if( pos == dataLength ) | |
{ | |
pos = -1; | |
} | |
return pos; | |
} | |
unsafe static int IndexOfPointer( string data, char find ) | |
{ | |
fixed( char* begin = data ) | |
{ | |
char* ptr = begin; | |
char* end = begin + data.Length; | |
while( ptr < end ) | |
{ | |
if( *ptr == find ) | |
{ | |
break; | |
} | |
++ptr; | |
} | |
if( ptr == end ) | |
{ | |
return -1; | |
} | |
return ( int )( ptr - begin ); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.NET Framework 4.5.2, Release build | |
Core i7-4500U で実行 | |
--- Result --- | |
DefaultIndexOf: 00:00:00.3310381 | |
IndexOfIndexer: 00:00:01.5193548 | |
IndexOfPointer: 00:00:00.7990235 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment