0

This question makes it clear that it is safe to call memcpy passing zero as the number of bytes to copy. However, the implementation of Lua avoids doing this, claiming empty memcpy "may be expensive", or at least, is "not that cheap".

I would have thought that calling memcpy with a zero count would be more-or-less free - could it be expensive in certain situations?

user200783
  • 13,722
  • 12
  • 69
  • 135
  • 2
    Compared to what? It's not free, but it is cheap, but if you're going to call it gazillions of times per second it is certainly not free. – user207421 Jul 27 '19 at 08:38
  • 3
    The real question is whether adding a check for a zero count to your code is more expensive that relying on the check that `memcpy` makes. The answer is *it depends*. – john Jul 27 '19 at 08:40
  • 4
    For any/all questions regarding performance you need to measure with your tool chain, on your platform and with your workload. Other people's testing in their environment(s) may give you a rough indication but not an expectation to get similar results yourself. – Richard Critten Jul 27 '19 at 08:45
  • 3
    Once upon a time a function call was significantly more expensive than an `if(n != 0)` test. But today that tends to be less true, and `memcpy` is likely to be inlined anyway, so it's probably a wash. – Steve Summit Jul 27 '19 at 09:31
  • @ArminMontigny Incorrect. It *can.* It *may* not be. Only measurements can tell, or an intimate acquiatance with the unnamed compiler. – user207421 Jul 27 '19 at 10:14
  • 2
    Ask the guy who made those commits in lua, he probably doesn't know what he's talking about. The unnecessary check is actually slowing down the code for no good reason. – rustyx Jul 27 '19 at 10:19
  • And, if the author did know that `memcpy` with zero length was slow for some reason, they were negligent not to provide information along with their statement. Such a claim ought to be supported by evidence so that future readers have reason to believe it and can adapt the code to changing circumstances. – Eric Postpischil Jul 27 '19 at 12:47

0 Answers0