We present a polynomial upper bound for flattening of UML statecharts. An efficient flattening technique is derived and implemented in SCOPE—a code generator targeting constrained embedded systems. Programs generated with this new technique are both faster and smaller than those produced by non-flattening code generators. Our approach scales well for big models and exhibits good properties with respect to memory usage, automatic analysis of worst-case reaction time and automatic validation of memory safety. Categories and Subject Descriptors D.2.2 [Software Engineering]: Design Tools and Techniques—State Diagrams General Terms Algorithms, Performance, Languages Keywords Program synthesis, automatic code generation, statecharts, semantics, embedded systems