py/obj: Add MICROPY_OBJ_IMMEDIATE_OBJS option to reduce code size.

This option (enabled by default for object representation A, B, C) makes
None/False/True objects immediate objects, ie they are no longer a concrete
object in ROM but are rather just values, eg None=0x6 for representation A.

Doing this saves a considerable amount of code size, due to these objects
being widely used:

   bare-arm:  -392 -0.591%
minimal x86:  -252 -0.170% [incl +52(data)]
   unix x64:  -624 -0.125% [incl -128(data)]
unix nanbox:    +0 +0.000%
      stm32: -1940 -0.510% PYBV10
     cc3200: -1216 -0.659%
    esp8266:  -404 -0.062% GENERIC
      esp32:  -732 -0.064% GENERIC[incl +48(data)]
        nrf:  -988 -0.675% pca10040
       samd:  -564 -0.556% ADAFRUIT_ITSYBITSY_M4_EXPRESS

Thanks go to @Jongy aka Yonatan Goldschmidt for the idea.
This commit is contained in:
Damien George
2020-01-09 00:00:27 +11:00
parent 6f0c83f6e1
commit d96cfd13e3
5 changed files with 59 additions and 12 deletions

View File

@@ -28,21 +28,31 @@
#include "py/runtime.h"
#if MICROPY_OBJ_IMMEDIATE_OBJS
#define BOOL_VALUE(o) ((o) == mp_const_false ? 0 : 1)
#else
#define BOOL_VALUE(o) (((mp_obj_bool_t*)MP_OBJ_TO_PTR(o))->value)
typedef struct _mp_obj_bool_t {
mp_obj_base_t base;
bool value;
} mp_obj_bool_t;
#endif
STATIC void bool_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
mp_obj_bool_t *self = MP_OBJ_TO_PTR(self_in);
bool value = BOOL_VALUE(self_in);
if (MICROPY_PY_UJSON && kind == PRINT_JSON) {
if (self->value) {
if (value) {
mp_print_str(print, "true");
} else {
mp_print_str(print, "false");
}
} else {
if (self->value) {
if (value) {
mp_print_str(print, "True");
} else {
mp_print_str(print, "False");
@@ -65,13 +75,13 @@ STATIC mp_obj_t bool_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
if (op == MP_UNARY_OP_LEN) {
return MP_OBJ_NULL;
}
mp_obj_bool_t *self = MP_OBJ_TO_PTR(o_in);
return mp_unary_op(op, MP_OBJ_NEW_SMALL_INT(self->value));
bool value = BOOL_VALUE(o_in);
return mp_unary_op(op, MP_OBJ_NEW_SMALL_INT(value));
}
STATIC mp_obj_t bool_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
mp_obj_bool_t *self = MP_OBJ_TO_PTR(lhs_in);
return mp_binary_op(op, MP_OBJ_NEW_SMALL_INT(self->value), rhs_in);
bool value = BOOL_VALUE(lhs_in);
return mp_binary_op(op, MP_OBJ_NEW_SMALL_INT(value), rhs_in);
}
const mp_obj_type_t mp_type_bool = {
@@ -83,5 +93,7 @@ const mp_obj_type_t mp_type_bool = {
.binary_op = bool_binary_op,
};
#if !MICROPY_OBJ_IMMEDIATE_OBJS
const mp_obj_bool_t mp_const_false_obj = {{&mp_type_bool}, false};
const mp_obj_bool_t mp_const_true_obj = {{&mp_type_bool}, true};
#endif