Thursday, July 15, 2004

Char VS VarChar

That is an interesting question posted on regarding the topic of Char or Varchar? - You Decide (by John Koziol). The question asked, Char data type is faster or VarChar?

While waiting for reply from John Koziol, I have a simple test on this as code below. The result is, using Char data type would be slighly faster than VarChar. The differences is about 100 - 200 miliseconds. Most importantly, this test is run on PII 266, 128 RAM, WinXP machine. You may not see any difference in fast machine. Therefore, in my opinion, you decide which data type you want to use.
CLEAR ALL


LOCAL lcUnique

SET TALK OFF

CREATE CURSOR myCursor (Field1 C(20))

FOR I = 1 TO 1000
lcUnique = SYS(2015)
INSERT INTO myCursor VALUES ;
(lcUnique + REPLICATE("A", INT(RAND() * 10)))
NEXT

INDEX ON Field1 TAG Field1

SET VARCHARMAPPING OFF

lnSecond = SECONDS()
FOR I= 1 TO 1000
SELECT * FROM myCursor WHERE .T. INTO CURSOR TEMP
NEXT

?SET("VARCHARMAPPING") + [ - ] + TRANSFORM(SECONDS() - lnSecond)

SELECT TEMP

lnSecond = SECONDS()
FOR I = 1 TO 100
LOCATE FOR Field1 = lcUnique
NEXT

?[LOCATE - ] + TRANSFORM(SECONDS() -lnSecond)
Instruction
1. Run the code above
2. Record the elapse time
3. Change setting SET VARMAPPING OFF to SET VARMAPPING ON, and run it again.

Do you get same result as me, CHAR would perform slightly faster than VarChar?
If my memory serve me right, one of UT member explained that, this behavior caused by VFP need extra steps to take care of VARCHAR.

For example, you have a Name field with VARCHAR data type, length 30. If user key in 15 characters, VFP would replace the remaining spaces with CHR(0), and last byte with the actual number of characters stored in this field, which is value 15 in this case.

0 Comments:

Post a Comment

<< Home