2011年12月19日 星期一

VB.net string into structure vs. substring

在上一篇文章中: VB.net String into structure

提到了 String 直接 copy 進 structure 的方式。因為之前一直都是用 Substring 的方式來作這個動作,最近才知道原來還有直接把字串放進 structure 的方法。

既然這個方式也成功的完成我想要的動作之後…那就開始想來比較一下兩者的時間差異了…

首先我們來試一下普通會遇到的情況…



以字串: abcdefgh2223333x123bbbkkkllleeerrriiioox999999999ggggggggggy55555mmmmmmmmm333xpppppppp

為例…我們來拆成 c01, c02, c03... 到 c15 這 15 個字串。

其實會遇到這個情況,通常是寫 socket 時會遇到的…當和對方的電文格式定義出來後…接下來要做的事就是如何去拆解接收到的電文。

所以才有會這樣子的需求。

接著來看看兩者比較用的程式:


Dim T1 As TimeSpan = New TimeSpan(System.DateTime.Now.Day, System.DateTime.Now.Hour, System.DateTime.Now.Minute, System.DateTime.Now.Second, System.DateTime.Now.Millisecond)

Dim buffer As String = "abcdefgh2223333x123bbbkkkllleeerrriiioox999999999ggggggggggy55555mmmmmmmmm333xpppppppp"

For i = 0 To 1000000
Dim pBuf As IntPtr = Marshal.StringToBSTR(buffer)
Dim ms As myStruct = CType(Marshal.PtrToStructure(pBuf, GetType(myStruct)), myStruct)
Marshal.FreeBSTR(pBuf)
Next

Dim T2 As TimeSpan = New TimeSpan(System.DateTime.Now.Day, System.DateTime.Now.Hour, System.DateTime.Now.Minute, System.DateTime.Now.Second, System.DateTime.Now.Millisecond)

MessageBox.Show(T2.Subtract(T1).ToString())


上面這個方式是用 string into structure 的方法作的,執行 10 萬次的結果在我的電腦上大概是 250 millisecond 上下(230~270)。

再來來看看 substring 的方式:


Dim c01 As String
Dim c02 As String
Dim c03 As String
Dim c04 As String
Dim c05 As String
Dim c06 As String
Dim c07 As String
Dim c08 As String
Dim c09 As String
Dim c10 As String
Dim c11 As String
Dim c12 As String
Dim c13 As String
Dim c14 As String
Dim c15 As String

Dim T1 As TimeSpan = New TimeSpan(System.DateTime.Now.Day, System.DateTime.Now.Hour, System.DateTime.Now.Minute, System.DateTime.Now.Second, System.DateTime.Now.Millisecond)

Dim buffer As String = "abcdefgh2223333x123bbbkkkllleeerrriiioox999999999ggggggggggy55555mmmmmmmmm333xpppppppp"


For i = 0 To 100000

c01 = buffer.Substring(0, 4)
c02 = buffer.Substring(4, 4)
c03 = buffer.Substring(8, 7)
c04 = buffer.Substring(15, 1)
c05 = buffer.Substring(16, 3)
c06 = buffer.Substring(19, 20)
c07 = buffer.Substring(39, 1)
c08 = buffer.Substring(40, 9)
c09 = buffer.Substring(49, 10)
c10 = buffer.Substring(59, 1)
c11 = buffer.Substring(60, 5)
c12 = buffer.Substring(65, 9)
c13 = buffer.Substring(74, 3)
c14 = buffer.Substring(77, 1)
c15 = buffer.Substring(78, 8)

Next



Dim T2 As TimeSpan = New TimeSpan(System.DateTime.Now.Day, System.DateTime.Now.Hour, System.DateTime.Now.Minute, System.DateTime.Now.Second, System.DateTime.Now.Millisecond)

MessageBox.Show(T2.Subtract(T1).ToString())



結果呢… 同樣執行 10 萬次跑出來的時間竟然是在 70 millisecond 上下!

所以…

讓我們繼續用 substring 吧!

沒有留言:

張貼留言

留言請留下大名~謝謝。

Related Posts Plugin for WordPress, Blogger...