Skip to content

Performance: string methods instead of new URL #79

Description

@DarkCat09

We'll get a really good performance boost if we replace new URL, which is used too much often as I see, with string methods. On the other hand, manually parsing URL in some cases is not simple and concise.

Benchmark code
const Benchmarkify = require("benchmarkify")

const benchmark = new Benchmarkify("Benchmark", { chartImage: true }).printHeader()

benchmark.createSuite("URL convert", { time: 10000 })

  .add("URL object", () => {
                const url = new URL("https://dc09.ru/posts/fediverse#comments")
                const hash = url.hash
                url.hash = ""
                return encodeURIComponent(url.toString()) + hash
        })

        .ref("String methods", () => {
                let url = "https://dc09.ru/posts/fediverse#comments"
                const hashIdx = url.indexOf("#")
                if (hashIdx != -1) {
                        return encodeURIComponent(url.substring(0, hashIdx)) + url.substring(hashIdx)
                }
                else {
                        return encodeURIComponent(url)
                }
        })

benchmark.run()
Benchmark results
Platform info:
==============
   Linux 6.7.4-artix1-1 x64
   Node.JS: 21.6.1
   V8: 11.8.172.17-node.19
   CPU: Intel(R) Core(TM) i5-10400 CPU @ 2.90GHz × 12
   Memory: 30 GB

Suite: URL convert
==================

✔ URL object         1 176 230 ops/sec
✔ String methods     4 825 419 ops/sec

   URL object           -75,62%   (1 176 230 ops/sec)   (avg: 850ns)
   String methods (#)        0%   (4 825 419 ops/sec)   (avg: 207ns)

┌────────────────┬────────────────────────────────────────────────────┐
│ URL object     │ ████████████                                       │
├────────────────┼────────────────────────────────────────────────────┤
│ String methods │ ██████████████████████████████████████████████████ │
└────────────────┴────────────────────────────────────────────────────┘

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions