My test with constants or with var strings is very bad = 540 ms !!!
So tell me what you are doing different ??? Where is the bug ??? I don't see it right now...
Concatenating strings makes things VERY slow. Try to avoid it as much as possible. Actually, I did the test using the FreeBASIC compiler as I was right in the middle of it, but FreePascal should give similar results. You could regard it as pseudo code if you wish:
#include "ifconsts.bi"
declare function Code(c as string) as integer
dim start as double
dim i as integer
dim c as string
dim n as integer
cls
c = "G999"
start = timer
for i = 1 to 100000
n = Code(c)
next
print timer - start
end
function Code(c as string) as integer
static n as integer
if c < G250 then
if c = G001 then
n = 1
elseif c = G002 then
n = 2
...
I used three main IF blocks (250, 500, 750) which improved the test by 2 seconds. The include file simply contains the constants:
const G001 = "G001"
const G002 = "G002"
const G003 = "G003"
...
Doing the same with arrays makes the code significantly shorter but not faster:
#include "aconsts.bi"
declare function Code(c as string) as integer
dim start as double
dim i as integer
dim c as string
dim n as integer
cls
c = "G999"
start = timer
for i = 1 to 100000
n = Code(c)
next
print timer - start
end
function Code(c as string) as integer
dim i as integer
if c < arr(250) then
for i = 1 to 249
if c = arr(i) then
return i
end if
next
elseif c < arr(500) then
for i = 250 to 499
if c = arr(i) then
return i
end if
next
elseif c < arr(750) then
for i = 500 to 749
if c = arr(i) then
return i
end if
next
end if
for i = 750 to 999
if c = arr(i) then
return i
end if
next
return 0
end function
Include file has the array definition:
dim shared arr(1 to 999) as string
arr(1) = "G001"
arr(2) = "G002"
arr(3) = "G003"
...
While the use of constants seem verbose, it is quite optimal for obvious reasons (predefined, fixed-length, etc). I'm not saying that either is the preferred way, as it is a bit more work to maintain, but it was interesting to compare speed. Yet, I would be crazy enough to do it like this if it would be faster.
As I said, I dumped the definitions in a matter of minutes and the same could be done for procedures:
open fname for output as #handle
for i = 1 to 999
buffer = "arr(" & i & ") = " + chr(34) + "G" + format(i, "000") + chr(34)
'buffer = format(i, "000")
'buffer = "const G" + buffer _
'+ " = " + chr(34) + "G" + buffer + chr(34)
'buffer = "elseif c = G" + format(i, "000") + " then"
'print #handle, buffer
'buffer = " return " & i
print #handle, buffer
next
close #handle