KeyDown Performance

I was just wondering when filtering keys in the KeyDown event, what’s faster, using case statement, logical OR, or InStr?

Thank you

depends on what you are filtering for…
if testing for in a range… probably logical OR

if key<"0" or key>"9" then

if testing for a specific small group … probably Instr

if instr("AZT",key)>0 then

If wanting different actions based on key… then Case Stmt

I’d say: it doesn’t matter. The user is the slowest part here.

Would you consider this a small group?

InStr("0123456789"+Chr(3)+Chr(8)+Chr(9)+Chr(13)Chr(28)+Chr(29)+Chr(30)+Chr(31)+Chr(127), Key)

I would consider that unreadable :slight_smile:

if (key>="0" and key<="9") or ascb(key)<32 or ascb(key)=127 then

Static chars As String = "0123456789"+Chr(3)+Chr(8)+Chr(9)+Chr(13)Chr(28)+Chr(29)+Chr(30)+Chr(31)+Chr(127) InStr(chars, Key)
… so the test string is only built once.

Me too, but I see it used so many times on the boards.

Why do you use AscB instead of Asc?

I would prefer a select case to maintain it easier.

I modified my code to this:

[code] dim isSeparator as Boolean

isSeparator = ( InStr( gDecimalSeparator, Key) > 0 ) // Decimal separator can be more than one character.

// If key entered by user is
if (key < “0” or Key > “9”) _ // not a number between 0 and 9
and ascb(Key) >= 32 _ // but is a printable character
and ascb(Key) <> 127 _ // and not delete
and not isSeparator then // and not a decimal separator
Return True // Don’t allow the keystroke to be entered into the field
end if

if isSeparator then
if me.Text.InStr( key ) > 0 then
me.Text = me.Text.ReplaceAll( key, “” )
end if
end if[/code]

What happens if you type 8.8 ?

I get 8.8

Is there something that I’m not seeing? Please let me know.

Sorry. My mistake. Misunderstood the gDecimalSeparator.

I’ve since taken out the code for the possibility the decimal separator being more than one character. That code wasn’t right. Also, I would imagine multiple characters for a decimal separator is a rare occurrence, especially for the type of app this is.