Skip to content

Commit

Permalink
Performance optimization: check for python float before type-checking…
Browse files Browse the repository at this point in the history
… numpy.

Checking whether the object is a numpy array checking is pretty expensive, so we only want to do it when the object is not trivially a float.

This makes appending to a repeated field of float ~3x faster in a common case:

```
_bench_append, 1000000, 284.1
_bench_extend, 1000000, 209.0
_bench_assign, 1000000, 175.8
_bench_pybind11, 1000000, 3.7
```

```
_bench_append, 1000000, 128.4
_bench_extend, 1000000, 67.1
_bench_assign, 1000000, 57.2
_bench_pybind11, 1000000, 3.5
```

PiperOrigin-RevId: 707811151
  • Loading branch information
protobuf-github-bot authored and copybara-github committed Dec 19, 2024
1 parent 0d47a29 commit 9e44913
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions python/convert.c
Original file line number Diff line number Diff line change
Expand Up @@ -217,15 +217,15 @@ bool PyUpb_PyToUpb(PyObject* obj, const upb_FieldDef* f, upb_MessageValue* val,
case kUpb_CType_UInt64:
return PyUpb_GetUint64(obj, &val->uint64_val);
case kUpb_CType_Float:
if (PyUpb_IsNumpyNdarray(obj, f)) return false;
if (!PyFloat_Check(obj) && PyUpb_IsNumpyNdarray(obj, f)) return false;
val->float_val = PyFloat_AsDouble(obj);
return !PyErr_Occurred();
case kUpb_CType_Double:
if (PyUpb_IsNumpyNdarray(obj, f)) return false;
if (!PyFloat_Check(obj) && PyUpb_IsNumpyNdarray(obj, f)) return false;
val->double_val = PyFloat_AsDouble(obj);
return !PyErr_Occurred();
case kUpb_CType_Bool:
if (PyUpb_IsNumpyNdarray(obj, f)) return false;
if (!PyBool_Check(obj) && PyUpb_IsNumpyNdarray(obj, f)) return false;
val->bool_val = PyLong_AsLong(obj);
return !PyErr_Occurred();
case kUpb_CType_Bytes: {
Expand Down

0 comments on commit 9e44913

Please sign in to comment.