dop251 / goja

ECMAScript/JavaScript engine in pure Go
MIT License
5.65k stars 381 forks source link

how to impove performance for a amount of constant literal in a javascript file #566

Closed pkujhd closed 6 months ago

pkujhd commented 7 months ago

I use goja as a runtime for execute javascript file. but when require text-encoding modules into goja's runtime. It's incredibly slow. I profile it, found most cost of cpu was in Goja (* Program). defineLiteralValue. the modules text-encoding has a amount of constant literal. Is there a way to improve performance?

thx~

pkujhd commented 7 months ago

I disable cache lookup with Program.values, the performance is same as node.  Could you give an option for goja.Compile to disable the cache lookup?

dop251 commented 7 months ago

Hi. Could you provide more details about the code you're running and how you're running it, and the change you made?

pkujhd commented 7 months ago

Hi. Could you provide more details about the code you're running and how you're running it, and the change you made?

@dop251 I execute javascript string "require(text-encoding)" text-encoding is a npm package (https://www.npmjs.com/package/text-encoding

when I change

func (p *Program) defineLiteralValue(val Value) uint32 {
    for idx, v := range p.values {
        if v.SameAs(val) {
            return uint32(idx)
        }
    }
    idx := uint32(len(p.values))
    p.values = append(p.values, val)
    return idx
}

to

func (p *Program) defineLiteralValue(val Value) uint32 {
    // for idx, v := range p.values {
    //  if v.SameAs(val) {
    //      return uint32(idx)
    //  }
    // }
    idx := uint32(len(p.values))
    p.values = append(p.values, val)
    return idx
}

the performance is close to node. this change disable cache lookup for literal values in Program

becasue text-encoding/lib/encoding-indexes.js have a amount of literal, every literal traverses search Program.values with many items, every item's compare it with SameAs function( it call reflect to cast type). it is a slow mechanism in this case

pkujhd commented 6 months ago

thanks, it's working