Created
June 6, 2014 13:36
-
-
Save AdrianV/c2f7efd0632006375517 to your computer and use it in GitHub Desktop.
OOP in nimrod via case statement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import benchmark | |
type | |
ClassID = enum CBase, CSecond, CThird | |
TBase = ref object {.inheritable.} | |
class: ClassID | |
data: int | |
TSecond = ref object of TBase | |
d2: int | |
TThird = ref object of TSecond | |
d3: int | |
proc foo_Impl(self:TBase): int = self.data | |
template multi_Impl(self: TBase; a,b,c: int): int = 0 | |
template init(self: TBase) = | |
self.data = 10 | |
self.class = CBase | |
proc newTBase(): TBase = | |
new(result) | |
init(result) | |
proc foo_Impl(self: TSecond): int = cast[TBase](self).foo_Impl() + self.d2 | |
template multi_Impl(self: TSecond; a,b,c: int): int = a + b + c | |
template init(self: TSecond) = | |
init(cast[TBase](self)) | |
self.class = CSecond | |
self.d2 = 12 | |
proc newTSecond(): TSecond = | |
new(result) | |
init(result) | |
proc foo_Impl(self: TThird): int = self.d3 | |
template multi_Impl(self: TThird; a,b,c: int): int = a + b + c + self.d3 | |
template init(self: TThird) = | |
init(cast[TSecond](self)) | |
self.class = CThird | |
self.d3 = 3 | |
proc newTThird(): TThird = | |
new(result) | |
init(result) | |
proc foo(self: TBase): int = | |
case self.class : | |
of CBase: foo_Impl(self) | |
of CSecond: foo_Impl(cast[TSecond](self)) | |
of CThird: foo_Impl(cast[TThird](self)) | |
proc multi(self: TBase; a,b,c: int): int = | |
case self.class : | |
of CBase: multi_Impl(self, a, b, c) | |
of CSecond: multi_Impl(cast[TSecond](self), a, b, c) | |
of CThird: multi_Impl(cast[TThird](self), a, b, c) | |
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 | |
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