So, I’m wrapping up a few sample projects that use my upcoming story/dialogue plugin and I decided to run some benchmarks. I know this is obvious to some, but I have been using Corona for almost five years and I never even considered how Corona loads fonts. So, this is for those two or three people wanting to optimise their games and who, like me, didn’t know about this yet.
Simply put, creating a text display object for the first time takes a really long time. Let’s assume I have four custom fonts and the following code:
scene.lua
local composer = require( "composer" ) local scene = composer.newScene() function scene:create( event ) local sceneGroup = self.view local text = {} local time = system.getTimer() local font for i = 1, 4 do if i == 1 then font = "fonts/OpenSans-Regular.ttf" elseif i == 2 then font = "fonts/OpenSans-Italic.ttf" elseif i == 3 then font = "fonts/OpenSans-Bold.ttf" else font = "fonts/OpenSans-BoldItalic.ttf" end text[i] = display.newText( "Hello World #"..i.."!", 160, 120+i\*32, font, 24 ) print( "\"Hello World #"..i.."!\" created in "..system.getTimer()-time.."ms." ) time = system.getTimer() end end scene:addEventListener( "create", scene ) return scene
The output is roughly
"Hello World #1!" created in 251.4ms. "Hello World #2!" created in 252.6ms. "Hello World #3!" created in 256.6ms. "Hello World #4!" created in 255.4ms.
So it takes roughly a quarter of a second to create a new text display object when using a new font for the first time, or over 1 second combined for all 4 fonts. This feels like an eternity to me because when I am creating text display objects, I want them immediately and not soon-ish.
So, if I add the following code to main.lua:
local composer = require ("composer") local text = {} local font for i = 1, 4 do if i == 1 then font = "fonts/OpenSans-Regular.ttf" elseif i == 2 then font = "fonts/OpenSans-Italic.ttf" elseif i == 3 then font = "fonts/OpenSans-Bold.ttf" else font = "fonts/OpenSans-BoldItalic.ttf" end text[i] = display.newText( "", 0, 0, font, 24 ) display.remove(text[i]) end composer.gotoScene("scene")
Then the output from scene.lua becomes:
"Hello World #1!" created in 0.5ms. "Hello World #2!" created in 0.4ms. "Hello World #3!" created in 0.5ms. "Hello World #4!" created in 0.3ms.
So, tldr: preload your fonts by creating a display object using them and delete them straight away.
Hopefully this was news to someone else as well and it helps you out. If it were up to me, I’d include a short disclaimer about how fonts are loaded in Corona’s documentation.