Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

This benchmark compares a duck typed call to a normal call. Duck Typing calls are about 160 times slower.

No Format
[Module]
class DuckBM:
	pass

def add(a as int, b as int):
	return a + b
def add(a as int, b as string):
	return a + int.Parse(b)
def add(a as string, b as int):
	return int.Parse(a) + b
def add(a as string, b as string):
	return int.Parse(a) + int.Parse(b)

print add(3,4), add(3, "4"), add("3", 4), add("3","4")

start = date.Now
i = 0
while i < 1000000:
	add(3,4)
	add(3,4)
	add(3,4)
	add(3,4)
	add(3,4)
	add(3,4)
	add(3,4)
	add(3,4)
	add(3,4)
	add(3,4)
	++i
elapsed = date.Now.Subtract(start)
print ("add elapsed time = $elapsed")

start = date.Now
i = 0
while i < 1000000:
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	(DuckBM as duck).add(3,4)
	++i
elapsed = date.Now.Subtract(start)
print ("duck elapsed time = $elapsed")

Output:

No Format
7 7 7 7
add elapsed time = 00:00:00.1101584
duck elapsed time = 00:00:16.5137456

Duck Typing Implementation

Boo's Duck Typing uses type.InvokeMember (System.Reflection), which can be very slow. To speed it up, you need to replace the duck types with static type casts (see Casting Types) or type declarations ("x as int").

Another example

See this thread. In the example, a million items of unknown type are added to a list after being upper-cased (if a string) or added (if an int).

Boo is pretty much as fast as other statically typed languages when you use static typing. It takes only .34 seconds to do this example on my machine.

But using Duck Typing or the -ducky option may make your code slower than regular Python (~1.5 seconds for boo with duck typing vs. ~1 second for Python). About 50% slower in this example. Note, I am not saying Python is slow. In fact Python + Psyco is just as fast (.32s) as optimized C# code in this particular example.