Skip to content

Instantly share code, notes, and snippets.

@AdrianV
Created June 6, 2014 13:41
Show Gist options
  • Save AdrianV/211bfceac562af218a7e to your computer and use it in GitHub Desktop.
Save AdrianV/211bfceac562af218a7e to your computer and use it in GitHub Desktop.
OOP nimrod style
import benchmark
type
TBase = ref object {.inheritable.}
data: int
TSecond = ref object of TBase
d2: int
TThird = ref object of TSecond
d3: int
method foo(self:TBase): int = self.data
method multi(self: TBase; a,b,c: int): int = 0
template init(self: TBase) =
self.data = 10
proc newTBase(): TBase =
new(result)
init(result)
method foo(self: TSecond): int = cast[TBase](self).foo() + self.d2
method multi(self: TSecond; a,b,c: int): int = a + b + c
template init(self: TSecond) =
init(cast[TBase](self))
self.d2 = 12
proc newTSecond(): TSecond =
new(result)
init(result)
method foo(self: TThird): int = self.d3
method multi(self: TThird; a,b,c: int): int = a + b + c + self.d3
template init(self: TThird) =
init(cast[TSecond](self))
self.d3 = 3
proc newTThird(): TThird =
new(result)
init(result)
var o: TBase
o = newTThird()
bench("TThird.multi"):
var c = 0
for i in 1..1_000_000_000:
c = o.Multi(i, i-1, i-2)
echo c
o = newTSecond()
bench("TSecond.multi"):
var c = 0
for i in 1..1_000_000_000:
c = o.Multi(i, i-1, i-2)
echo c
o = newTBase()
bench("TBase.multi"):
var c = 0
for i in 1..1_000_000_000:
c = o.Multi(i, i-1, i-2)
echo c
o = newTThird()
bench("TThird.Foo"):
var c = 0
for i in 1..1_000_000_000:
c = o.Foo()
echo c
bench("TThird create and Foo"):
var c = 0
for i in 1..10_000_000:
o = newTThird()
c = o.Foo()
echo c
when false: # this does not work in nimrod
o = newTSecond()
bench("TSecond.Foo"):
var c = 0
for i in 1..1_000_000_000:
c = o.Foo()
echo c
o = newTBase()
bench("TBase.Foo"):
var c = 0
for i in 1..1_000_000_000:
c = o.Foo()
echo c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment