본문으로 건너뛰기
Previous
Next
C++ Array vs vector: Performance, Safety, and When to Use

C++ Array vs vector: Performance, Safety, and When to Use

C++ Array vs vector: Performance, Safety, and When to Use

이 글의 핵심

C-style arrays, std::array, and std::vector compared: stack vs heap, fixed vs dynamic size, bounds checking, benchmarks, and practical choice guide.

For arrays vs linked lists in algorithm interviews (cache locality, insertion cost), see [arrays and lists](/en/blog/algorithm-series-01-array-list/—it complements choosing among C++ array flavors here.

Introduction: “Array or vector?"

"I heard arrays are faster, but everyone says use vector”

C++ offers C-style arrays, std::array, and std::vector. They differ in storage, resize capability, and safety.

int arr1[5] = {1, 2, 3, 4, 5};
std::array<int, 5> arr2 = {1, 2, 3, 4, 5};
std::vector<int> vec = {1, 2, 3, 4, 5};

This article covers:

  • Differences among the three
  • Performance benchmarks
  • Memory safety
  • Selection guide

Table of contents

  1. Three array kinds
  2. Benchmarks
  3. Memory safety
  4. Selection guide
  5. Summary

1. Three array kinds

Comparison table

AspectC arraystd::arraystd::vector
StorageUsually stackUsually stackHeap
SizeFixed (compile-time)Fixed (compile-time)Dynamic
Bounds checkNoat()at()
Size querysizeof hackssize()size()
STL algorithmsPartialFullFull
Function argsDecays to pointerBy value/refTypically const ref
SafetyLowHighHigh

C-style array pitfalls

int arr[5] = {1, 2, 3, 4, 5};
// arr[10] = 99;  // undefined behavior
void foo(int arr[]) { /* sizeof(arr) is pointer size */ }

std::array (C++11)

#include <array>
std::array<int, 5> arr = {1, 2, 3, 4, 5};
arr.at(10);  // throws std::out_of_range
std::sort(arr.begin(), arr.end());

std::vector

#include <vector>
std::vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6);
vec.resize(10);
vec.at(10);  // throws if out of range

2. Benchmarks

Test 1: element access

Result (typical optimized builds): same order of magnitude for indexed access over large iteration counts.

Test 2: create/destroy in a loop

Stack arrays / std::array: cheap construction.
vector: heap allocation/deallocation dominates if you repeatedly create huge vectors in inner loops.

Test 3: iteration

Range-for and indexed loops are typically comparable when optimized.

3. Memory safety

Bounds checking

Use at() when you want exceptions on out-of-range access; operator[] is unchecked (fast, sharp).

Passing arrays to functions

Prefer std::array<T,N> or const std::vector& so length travels with the data.

4. Selection guide

Decision sketch

Fixed size known at compile time?
  No  -> std::vector
  Yes -> Small (< ~100) -> std::array often fine
         Large buffer    -> vector (avoid huge stack frames)

Recommendations

SituationPrefer
Defaultstd::vector
Small fixed buffer, hot ctor/dtorstd::array
Dynamic sizestd::vector
Interop with C APIsraw arrays only at the boundary

Examples

Fixed small buffer:

std::array<char, 1024> buffer;
readData(buffer.data(), buffer.size());

Dynamic list:

std::vector<int> numbers;
numbers.reserve(100);
for (int i = 0; i < n; ++i) numbers.push_back(i);

3D coordinate:

struct Position {
    std::array<float, 3> coords;
};

Summary

Default: std::vector.
Fixed small N: std::array.
Avoid raw C arrays except FFI boundaries. Next: read the vector deep-dive in the series.

Keywords

array vs vector, std::array, stack vs heap, C++ performance

Practical tips

  • Use at() in debug-heavy workflows; keep [] where you have proven invariants.
  • reserve() for known growth patterns.
  • Watch stack size for large std::array locals.


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. C-style arrays, std::array, and std::vector compared: stack vs heap, fixed vs dynamic size, bounds checking, benchmarks,… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • [Arrays and Lists](/en/blog/algorithm-series-01-array-list/
  • C++ vector 기초 완벽 가이드 | 초기화·연산·용량 관리와 실전 패턴
  • C++ 스택 vs 힙 | 재귀에서 프로그램이 죽는 이유와 스택 오버플로우 사례

이 글에서 다루는 키워드 (관련 검색어)

C++, array, vector, std::array, performance, memory safety, STL 등으로 검색하시면 이 글이 도움이 됩니다.