Skip to content

Instantly share code, notes, and snippets.

@danielmatz
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielmatz/1a64cded91f996d40b99 to your computer and use it in GitHub Desktop.
Save danielmatz/1a64cded91f996d40b99 to your computer and use it in GitHub Desktop.
Understanding the Cost of Virtualization
type ChildA
end
type ChildB
end
increment(c::ChildA, x) = x + 1
increment(c::ChildB, x) = x + 2
type Container
i::Int
ca::ChildA
cb::ChildB
end
function increment(c::Container, x)
if c.i == 1
return increment(c.ca, x)
elseif c.i == 2
return increment(c.cb, x)
else
error("bad model selector")
end
end
function run(n)
sum = 0
container = Container(1, ChildA(), ChildB())
for i in 1:n
sum = increment(container, sum)
end
container.i = 2
for i in 1:n
sum = increment(container, sum)
end
@show sum
end
run(10)
@time run(10000000)
abstract Parent
type ChildA <: Parent
end
type ChildB <: Parent
end
incrementA(x) = x + 1
incrementB(x) = x + 2
type Container
p::Parent
end
function increment(c::Container, x)
if isa(c.p, ChildA)
return incrementA(x)
elseif isa(c.p, ChildB)
return incrementB(x)
end
end
function run(n)
sum = 0
container = Container(ChildA())
for i in 1:n
sum = increment(container, sum)
end
container.p = ChildB()
for i in 1:n
sum = increment(container, sum)
end
@show sum
end
run(10)
@time run(10000000)
abstract Parent
type ChildA <: Parent
end
type ChildB <: Parent
end
increment(c::ChildA, x) = x + 1
increment(c::ChildB, x) = x + 2
type Container
p::Parent
end
increment(c::Container, x) = increment(c.p, x)
function run(n)
sum = 0
container = Container(ChildA())
for i in 1:n
sum = increment(container, sum)
end
container.p = ChildB()
for i in 1:n
sum = increment(container, sum)
end
@show sum
end
run(10)
@time run(10000000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment