RS-MET icon indicating copy to clipboard operation
RS-MET copied to clipboard

std::function performance overhead

Open RobinSchmidt opened this issue 7 years ago • 4 comments

i did some performance measurements on various ways for implementing callbacks. here are my results:

  // results:                  cycles  bytes
  // function pointer:         23       8
  // functor:                   4       1
  // member function pointer:   8       1
  // std::function, lambda:    11      64
  // std::function, pointer:   26      64
  // std::function, functor:   11      64
  // std::function, member:    11      64

the member function pointer is what i use in Parameter, std::function is what you use. std::function takes 11 cpu-cycles per call whereas my member function pointer takes only 8. also, the memory occupation is much higher for std::function. ...although, i wonder, how a memory occupation of 1 byte is even possible. i mean, the memory occupation of a pointer is actually supposed to be equal to the native number of bits of the machine - which is 64 (= 8 bytes) in this case (or 32 (= 4 byte) for a 32 bit build). weird - but that's what sizeof returned. also weird is the bad performance of regular plain old c-style function-pointers.

sooo - my old way of doing this is actually more performant. of course std::function is more flexible and easier to use. don't know what to do with these figures now. ...maybe i could templatize the Parameter class on the callback type to allow anything. hmmm...

RobinSchmidt avatar Feb 03 '18 11:02 RobinSchmidt

i've done this because i was considering to switch to use std::function also myself and maybe throw away my old stuff. it's highly unelegant to have these two alternative ways in class Parameter. ...but considering the better performance and lower memory occupation of my old way, i think, i don't want to throw that code away

RobinSchmidt avatar Feb 03 '18 11:02 RobinSchmidt

the most elegant solution would perhaps be indeed to templatize the Parameter class on the the callback type. then, i would also not have to have 3 different callback members for double, int and bool setters (which is very inelegant in itself).

RobinSchmidt avatar Feb 03 '18 11:02 RobinSchmidt

this is not immediately urgent - it doesn't make or break any functionality, it's an optimization thing - but something, we may consider in the mid term

RobinSchmidt avatar Feb 04 '18 02:02 RobinSchmidt

sounds good, maybe ill switch over to more elegant function pointer when you implement it.

elanhickler avatar Feb 07 '18 00:02 elanhickler