Why doesn't adding a function to a struct make its instances larger?

68 Views Asked by At
struct A {
  var a:Int = 2
  
  func f()->Int {
    return 2*a
  }
}

var obj = A()
obj.f()

Size of obj is 8 bytes. And if I add new properties the size will be changed. It's fine.

I would like to know how compiler takes care about function's memory. No matter there is func in the struct or not, the size is the same. But func is information as well and I guess it should take memory as well(maybe I am wrong). So how that process is going on?

I would be so appreciated if you recommend me subject name so I can read.

Thanks

1

There are 1 best solutions below

0
Alexander On

Even though the function f appears nested in the struct A as far as the source-code appears, that isn't what actually happens in the compiled binary.

There's only one implementation of f, and it's shared among all instances of A. It's stored in the global program text, not unlike any other free function.

Although C++ focused, you get get more info on https://en.wikipedia.org/wiki/Virtual_method_table