What is the cost of sizeof?

前端 未结 7 1767
一向
一向 2021-02-05 10:06

What is the cost of sizeof?

I would expect:

  • sizeof(someclass) can be known at compile time
  • sizeof(someStaticArray) can be known at compile time
7条回答
  •  悲哀的现实
    2021-02-05 10:27

    In C++, the last case does not exist. sizeof can always be evaluated at compile time, based entirely on the type of the parameter, so the parameter itself is never evaluated.

    If you want something like a dynamic array in C++, you generally use std::vector, in which case there is a run-time cost, but the cost is extremely minor -- O(1). The difference in speed between sizeof and some_vector.size() is rarely relevant. The main one is that since size() isn't a constant, there may be some lost possibility for optimization -- e.g., N/sizeof(short) will usually be optimized to a right shift instead of an actual division, because sizeof(short) is a power of 2. Since the compiler won't normally know that whatever.size() is a power of 2, it has to use an actual division in that case. At the same time, most CPUs optimize division by a power of 2, so the difference remains very small.

    Edit (since the question has been retagged as C): C (since C99) provides both Variable Length Arrays (VLAs) and Flexible Array Members (FAMs). For a variable length array, sizeof does evaluate its parameter, so there is a (minimal) run-time cost -- roughly equivalent to std::vector::size() in C++. For all other types (including structs that include flexible array members), sizeof does not evaluate its operand, so there is no run-time cost (the same as in C++).

    For a struct with a flexible array member: "the size of the structure shall be equal to the offset of the last element of an otherwise identical structure that replaces the flexible array member with an array of unspecified length." (C99, §6.7.2.1/16).

提交回复
热议问题