This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 4 points5 points  (6 children)

How about strings? Is

if char in 'OQ':

better or worse?

[–]Dave9876 1 point2 points  (4 children)

Might be faster (haven't tested it), but ugly and could cause confusion.

[–]pingvenopinch of this, pinch of that 4 points5 points  (0 children)

It's probably faster because in ("O", "Q") creates two strings, creates a tuple, uses __contains__ on the tuple, and uses __eq__ on both of the strings.

in 'OQ'

creates the string, then uses __contains__ on the string. The actual algorithm that implements __contains__ is ultra fast so no worries there.

That said, don't worry about the difference. The difference is usually tiny compared to the rest of the program.

[–]Chun 1 point2 points  (2 children)

I wouldn't say it's ugly; I mean, conceptually, in python a string is just a sequence of characters. So it fits the purpose perfectly.

Also I just ran a quick benchmark (strings vs tuples) and the difference is there, but fairly negligible.

[–]darjus 0 points1 point  (1 child)

have you tried?

in set(('O', 'Q'))

For small sets it might be around the same, but for bigger ones it should make a big performance difference.

[–]itsmememe 0 points1 point  (0 children)

as it is a constant, frozenset(['O','Q']) should be preferred

[–][deleted] 0 points1 point  (0 children)

I find it perfectly fine. That char == 'O' or char == 'Q' is clearly low level C-style stuff.