vexflow
                                
                                
                                
                                    vexflow copied to clipboard
                            
                            
                            
                        StaveNote constructor is a performance bottleneck
I was profiling my application and I was surprised that the largest chunk of time (about 1/3) is spent in the StaveNote constructor. Not the formatter (1/6th) or the draw routines (also about 1/3) which I expected. (the rest is my application stuff).
Is this expected? The majority of the time is spent in different 'reset' functions and buildNoteHeads. Also I may be reading the Chrome call diagram wrong. But this diagram seems consistent with what I observe when profiling the parts of my application that create the notes vs. the parts that render the things.
EDIT: I realize part of the issue is that I'm setting the stem direction on the constructor, and also calling setStemDirection which just does the same thing. Once that is fixed, the time spent is less but still significant. It's not clear why autoStem and reset take so long. Updated diagram to show this.

I dug in here, and it doesn't seem that off to me -- there's a lot going on while initializing a note (which includes loading fonts and calculating widths), and if you have lots of them, it seems reasonable that it would dominate the time.
If you find something that's clearly off then I can dig deeper.
FWIW, PR #1103 should have gone some way to speeding up the StaveNote constructor by caching the glyph width calculations. (In fact, looking into why the StaveNote constructor took so much time was how I ended up writing that PR in the first place.)
It does look like the glyph is being looked up twice, once in the StaveNote constructor and once in the Note constructor.
Some small things:
- glyph_font_scale can probably be moved from StaveNoteStruct to NoteStruct since it's a property of Note not just StaveNote.
 - parseDuration could probably have a few of the most common values cached and avoid the 
regexp.exec(). - It might be better to defer buildFlag if possible, in case it's wiped out by adding a beam later.
 
But nothing that should make an enormous performance boost.
Thanks for looking! There have already been some improvements since I wrote this, mostly in the glyph cache. I have considered just closing it and re-opening when I have some time to investigate more.