Skip to content

Instantly share code, notes, and snippets.

@AdrianV
Created June 6, 2014 13:39
Show Gist options
  • Save AdrianV/140343ad5980d369139c to your computer and use it in GitHub Desktop.
Save AdrianV/140343ad5980d369139c to your computer and use it in GitHub Desktop.
OOP via VTables
import oopHelper, benchmark
declClass TBase:
var
data: int
proc create(data: int) {.constructor.} =
self.data = data
method Foo(): int = return self.data
method Multi(a, b, c: int): int = 0
proc initialize() {.inline.} =
self.data = 10
method Blah() =
self.data = 3
declClass TSecond, TBase:
var
d2: int
method Foo(): int {.override.} = Inherited(self).Foo(self) + self.d2
method Multi(a, b, c: int): int {.override.} = a + b + c
method Bar(): int = 0
proc initialize() {.inline.} =
initialize(super(self))
self.d2 = 12
declClass TThird, TSecond:
var
d3: int
method Foo(): int {.override.} = self.d3
method Bar(): int {.override.} = 3
method Multi(a, b, c: int): int {.override.} = a + b + c + self.d3
proc initialize() {.inline.} =
initialize(super(self))
self.d3 = 3
var o: TBase
o = TThird.newInstance()
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 = TSecond.newInstance()
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 = TBase.newInstance()
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 = TThird.newInstance()
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 = TThird.newInstance()
c = o.Foo()
echo c
o = TSecond.newInstance()
bench("TSecond.Foo"):
var c = 0
for i in 1..1_000_000_000:
c = o.Foo()
echo c
o = TBase.newInstance()
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