If you're reading from a file and appending to a string a lot and
this string is going to grow pretty large, your application can
benefit significantly if you preallocate a block of memory and resize
it only when needed. With strings, each time you assign to a string
you're going to be reallocating a chunk of memory for the string. If
you cut down the allocations to one or just a handful, it can speed
up things significantly.
I wrote a very small quick class called CapacityString to show this
and a quick demo app to test it.
For a 1.7 MB file, reading in 2 KB chunks with a BinaryStream a
standard loop like that below takes about 8.5 seconds.
for i = 1 to length step 2048
s = s + bin.Read(2048)
next
Now by comparison, using a CapacityString, I can read a 27 MB file
and it takes 0.15 seconds. No joke.
Here's the code for the class:
Class CapacityString
Properties:
mCapacity as Integer
mData as MemoryBlock
mLength as Integer
Methods:
Sub Constructor(capacity as Integer)
mCapacity = Capacity
mData = New MemoryBlock(mCapacity)
End Sub
Sub SetString(s as String)
dim slen as Integer = LenB(s)
if mCapacity < slen then
mCapacity = slen
mData.Size = mCapacity
end if
mData.StringValue(0, slen) = s
mLength = slen
End Sub
Sub AppendString(s as String)
dim slen as Integer = LenB(s)
if mCapacity < mLength + slen then
mCapacity = mLength + slen
mData.Size = mCapacity
end if
mData.StringValue(mLength, slen) = s
mLength = mLength + slen
End Sub
Sub InsertString(location as Integer, s as String)
dim slen as Integer = LenB(s)
if mCapacity < mLength + slen then
mCapacity = mLength + slen
mData.Size = mCapacity
end if
// memoryblock is 0 based
location = location - 1
mData.StringValue(location + slen, mLength - location) =
mData.StringValue(location, mLength - location)
mData.StringValue(location, slen) = s
mLength = mLength + slen
End Sub
Function Operator_Convert() As String
return mData.StringValue(0, mLength)
End Function
Enjoy your speed up!
Seth Willits
----------------------------------------------------------
Freak Software - http://www.freaksw.com/
ResExcellence - http://www.resexcellence.com/realbasic/
----------------------------------------------------------
_______________________________________________
Unsubscribe or switch delivery mode:
<http://www.realsoftware.com/support/listmanager/>
Search the archives of this list here:
<http://support.realsoftware.com/listarchives/lists.html>