Sub topic 9
Measuring Memory and Speed
This chapter shows how to measure what a text column costs in memory and time, so you can choose between object, string with the python backend, string with the pyarrow backend, and category using your own data.
It assumes you know the earlier material: object versus string columns, how pd.NA propagates through .str methods, and the python and pyarrow storage backends. It also assumes you can run a Python script and read a Series.
Why measure instead of guess
General advice about text columns is usually right in direction and wrong in size. "pyarrow uses less memory" holds for many columns. How much less depends on string length, how many strings are missing, and how often values repeat. "category is smaller" is true for a column with 500 distinct values in 200,000 rows. It can be larger when almost every value is unique.
The questions worth answering for a given column are:
- How many bytes does each representation use?
- How long do the operations I run on this column take?
- What does it cost to convert from my current representation?
The sections below answer each one with code you can run on your own data.
What memory_usage reports
Series.memory_usage has a deep argument that changes what is counted.
| Call | What it counts | Typical use |
|---|---|---|
| `memory_usage(deep=False)` | The array's own buffer. For `object` this is 8 bytes per element, one pointer to each Python object. | Fast, but misleading for text. |
| `memory_usage(deep=True)` | The buffer plus the size of each referenced Python object, via `sys.getsizeof`. | The number to compare for `object` and python-backed `string`. |
| `memory_usage(index=False)` | Excludes the index from either count. | Comparing columns without index noise. |
An object column of 200,000 short strings reports about 1.6 MB with deep=False, which is only the pointers. The real cost includes every str object, each with a header of around 49 bytes plus its characters. For text, always use deep=True.
The pyarrow backend does not hold Python objects. It stores one buffer of UTF-8 bytes, a buffer of offsets that marks where each string starts, and a validity bitmap for missing entries. Its shallow and deep numbers are therefore close to each other.
A memory comparison you can run
This script builds the same 200,000 values in each representation and prints shallow and deep sizes. The values come from 500 distinct strings, so repetition is high.
import importlib.util
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
words = np.array([f"customer-{i:05d}" for i in range(500)])
values = rng.choice(words, size=200_000).tolist()
candidates = {
"object": pd.Series(values, dtype=object),
"string[python]": pd.Series(values, dtype=pd.StringDtype("python")),
"category": pd.Series(values, dtype="category"),
}
if importlib.util.find_spec("pyarrow") is not None:
candidates["string[pyarrow]"] = pd.Series(
values, dtype=pd.StringDtype("pyarrow")
)
for name, s in candidates.items():
shallow = s.memory_usage(deep=False, index=False)
deep = s.memory_usage(deep=True, index=False)
print(f"{name:16} shallow={shallow:>10,} deep={deep:>10,}")Exact numbers depend on your pandas, pyarrow, and Python versions, so run it yourself. The pattern to expect is this:
objectandstring[python]have nearly the same deep size, because both hold one Pythonstrper element.string[pyarrow]is smaller, because it stores raw bytes with no per-object header.categoryis smallest here. It stores each of the 500 distinct strings once, plus one small integer code per row. pandas picks the smallest integer type that fits, which isint16for 500 categories.
Shared objects are counted repeatedly
deep=True adds up sys.getsizeof for each element. If many elements point to the same Python object, as happens when Python interns short strings or when you build a column from a small list of shared literals, each reference is counted again. The reported size can then be larger than what the process actually uses.
The script above avoids this because tolist() on a NumPy string array creates a new str for each element. When your data comes from a file or a database cursor, treat the object number as an upper bound. For a check at the process level, compare resident memory before and after loading the column.
Measuring speed
For timing, run the same operation several times and keep the minimum. The minimum is the run least disturbed by other work on your machine. Compare relative times between representations, not absolute values.
import importlib.util
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
words = np.array([f"customer-{i:05d}" for i in range(500)])
values = rng.choice(words, size=200_000).tolist()
candidates = {
"object": pd.Series(values, dtype=object),
"string[python]": pd.Series(values, dtype=pd.StringDtype("python")),
"category": pd.Series(values, dtype="category"),
}
if importlib.util.find_spec("pyarrow") is not None:
candidates["string[pyarrow]"] = pd.Series(
values, dtype=pd.StringDtype("pyarrow")
)
def best_time(func, repeat=5):
times = []
for _ in range(repeat):
start = time.perf_counter()
func()
times.append(time.perf_counter() - start)
return min(times)
operations = {
"upper": lambda s: s.str.upper(),
"contains": lambda s: s.str.contains("00", regex=False),
"len": lambda s: s.str.len(),
"equals": lambda s: s == "customer-00042",
"value_counts": lambda s: s.value_counts(),
}
print(f"{'dtype':16}" + "".join(f"{op:>14}" for op in operations))
for name, s in candidates.items():
row = f"{name:16}"
for op in operations.values():
row += f"{best_time(lambda: op(s)) * 1000:>12.2f}ms"
print(row)Things to look for in the output:
string[python]runs close toobject. Both call a Python function for each element. The difference is mostly the missing-value handling.string[pyarrow]is often faster on methods that Arrow implements as native kernels, such asupper,len,contains, and equality. Some.strmethods have no Arrow kernel in pandas, and for those pandas falls back to a per-element Python path. A fallback can be as slow asobject, or slower once conversion is included.categoryis fast for==andvalue_counts, because they work on integer codes. For.strmethods, pandas applies the operation to the distinct categories and maps the result back to the rows. With few categories this is fast, and with many unique values it is not.
Count the conversion too
A faster representation only pays off if the savings exceed the cost of getting there. Measure the conversion with the same timer.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(1)
words = np.array([f"item-{i:06d}" for i in range(50_000)])
obj = pd.Series(rng.choice(words, size=500_000).tolist(), dtype=object)
start = time.perf_counter()
converted = obj.astype("string")
convert_s = time.perf_counter() - start
start = time.perf_counter()
for _ in range(10):
obj.str.upper()
object_s = (time.perf_counter() - start) / 10
start = time.perf_counter()
for _ in range(10):
converted.str.upper()
string_s = (time.perf_counter() - start) / 10
print(f"conversion: {convert_s * 1000:8.1f} ms")
print(f"object upper: {object_s * 1000:8.1f} ms")
print(f"string upper: {string_s * 1000:8.1f} ms")If you convert once and then run many operations, the conversion cost is spread across them. If you convert and then run one .str call, you may lose time overall. The best place to convert is at load time, for example pd.read_csv(path, dtype={"name": "string"}), so the data never exists as object in the first place.
Conversion also needs memory. While astype runs, the original and the new column both exist, so peak memory is roughly the sum of both. This matters when the column is already close to your memory limit. Convert one column at a time and drop the old one.
Choosing from the measurements
The numbers lead to different decisions depending on the shape of the column.
| Column shape | Likely best choice | What to verify |
|---|---|---|
| Long, mostly unique text such as comments or addresses | `string[pyarrow]` | Deep memory is lower than `object`, and your `.str` methods have Arrow kernels. |
| Short codes with a few hundred distinct values over many rows | `category` | `memory_usage(deep=True)` is much smaller, and you do not need many `.str` transforms per row. |
| Text where you only ever filter and display | Either `string` backend | The simplest option that handles `pd.NA` consistently. |
| Small data of a few thousand rows | Whatever is clearest | Differences are too small to matter. |
| Environment without pyarrow | `string[python]` | Mainly gives consistent missing-value behavior, not memory savings. |
For columns with repeated values, a rule of thumb is to compare nunique() with len(). If the ratio of distinct values to rows is below roughly 0.5, category is worth testing. This is a starting point, not a threshold. Measure the column.
Pitfalls when benchmarking
- Tiny inputs. With a few hundred rows, timing is dominated by fixed overhead per call. Use at least 100,000 rows to see differences.
- Single runs. The first call can include warm-up. Use repeated runs and the minimum.
- Synthetic data. Randomly generated strings of equal length can hide the effect of long strings, Unicode text, and missing values. Test on a sample of your real column. A 5% sample often preserves the shape well enough.
- Different results. Two representations can return different result types. For example,
str.containsgivesboolonobjectcolumns without missing values, and nullablebooleanonstringcolumns. Check that outputs are equivalent before comparing times. - Ignoring the index.
memory_usage()includes the index by default. Passindex=Falsewhen you only want the column. - Version drift. Defaults change between pandas 2 and pandas 3, and so do the available Arrow kernels. Record the versions with
pd.__version__andpyarrow.__version__next to your results.
A checklist for a column
- Print
s.dtype,len(s),s.nunique(), ands.isna().sum(). - Compare
memory_usage(deep=True, index=False)forobject,string[python],string[pyarrow], andcategory. - Time the two or three operations you actually run, with repeated runs.
- Time the conversion, and decide whether to do it at load time.
- Confirm that results are equivalent across representations.
- Pick the simplest option that meets your memory and time limits.
Exercise
A colleague reports that an object column of 1,000,000 short strings uses only about 8 MB according to s.memory_usage(), so they say converting to a string dtype is pointless. What is wrong with this measurement, and what should they run instead?
Show answer
memory_usage() defaults to deep=False, which for an object column counts only the 8-byte pointers (1,000,000 x 8 bytes = 8 MB) and ignores the Python str objects they point to. They should run s.memory_usage(deep=True, index=False) for the object column and for each candidate representation, such as s.astype(pd.StringDtype("pyarrow")) and s.astype("category"), then compare the deep numbers. They should also treat the object figure as an upper bound if many elements are shared objects, since deep counting adds each reference separately.
Exercise
You timed s.str.upper() on string[pyarrow] and found it fast, but a different method on the same column was no faster than on object. Give a likely reason and a way to confirm it.
Show answer
That method probably has no native Arrow kernel in your pandas version, so pandas falls back to calling a Python function on each element, which gives object-like speed. To confirm, time the method on object, string[python], and string[pyarrow] with the same data. If the pyarrow time matches the other two, the fallback is the cause. Also check whether a different method, or a vectorized expression such as == or isin, can do the same job natively.