Hacker News new | ask | show | jobs
by properparity 870 days ago

  Vector* vector_create(size_t itemSize) {
    Vector* vec = (Vector*)malloc(sizeof(Vector));
    // ...
    return vec;
  }
This just immediately strike me as poor code.

C is not java, you do not have to "new" up every little structure.

  void vector_init(Vector *v, size_t itemSize) {
    v->itemSize = itemSize;
    // ...
  }
Instantly cleaner, more efficient, less memory allocation/handling needed, lets the user control where the Vector is stored.
2 comments

The new operator in Java doesn't always heap allocate, it depends on the JIT and escape analysis, it might be stack/register allocated if proven safe to do so.
Assuming that vector is just a dataptr/size/capacity triplet, vector create can just return by value.