搜索
首页web前端js教程Encore.ts — 比 ElysiaJS 和 Hono 更快

Beberapa bulan lalu kami mengeluarkan Encore.ts — rangka kerja bahagian belakang Sumber Terbuka untuk TypeScript.

Memandangkan terdapat banyak rangka kerja di luar sana, kami ingin berkongsi beberapa keputusan reka bentuk yang luar biasa yang telah kami buat dan cara ia membawa kepada angka prestasi yang luar biasa.

Penanda aras prestasi

Kami sebelum ini telah menerbitkan penanda aras yang menunjukkan bagaimana Encore.ts adalah 9x lebih pantas daripada Express dan 2x lebih pantas daripada Fastify.

Kali ini kami telah menanda aras Encore.ts terhadap ElysiaJS dan Hono, dua rangka kerja TypeScript berprestasi tinggi moden.

Kami menanda aras setiap rangka kerja dengan dan tanpa pengesahan skema, menggunakan TypeBox untuk pengesahan dengan ElsyiaJS dan Hono kerana ia adalah perpustakaan pengesahan asli yang disokong untuk rangka kerja ini. (Encore.ts mempunyai pengesahan jenis terbina dalam sendiri yang berfungsi dari hujung ke hujung.)

Untuk setiap penanda aras kami mengambil keputusan terbaik daripada lima larian. Setiap larian dilakukan dengan membuat permintaan sebanyak mungkin dengan 150 pekerja serentak, melebihi 10s. Penjanaan beban dilakukan dengan oha, alat ujian beban HTTP berasaskan Rust dan Tokio.

Cukup cakap, jom tengok nombor!

Permintaan sesaat: Encore.ts adalah 3x lebih pantas daripada ElysiaJS & Hono apabila menggunakan pengesahan jenis

Encore.ts — faster than ElysiaJS & Hono

(Lihat kod penanda aras pada GitHub.)

Selain prestasi, Encore.ts mencapai ini sambil mengekalkan 100% keserasian dengan Node.js.

Cara ia berfungsi: Keputusan reka bentuk yang lebih luar biasa

Bagaimana ini boleh berlaku? Daripada ujian kami, kami telah mengenal pasti tiga sumber prestasi utama, semuanya berkaitan dengan cara Encore.ts berfungsi di bawah hud.

1. Encore.ts berbilang benang dan dikuasakan oleh masa jalan Rust

Node.js menjalankan kod JavaScript menggunakan gelung acara berbenang tunggal. Walaupun sifatnya berbenang tunggal, ini agak berskala dalam amalan, kerana ia menggunakan operasi I/O yang tidak menyekat dan enjin JavaScript V8 asas (yang turut menggerakkan Chrome) sangat dioptimumkan.

Tetapi anda tahu apa yang lebih pantas daripada gelung acara berbenang tunggal? Berbilang benang.

Encore.ts terdiri daripada dua bahagian:

  1. SDK TypeScript yang anda gunakan semasa menulis hujung belakang menggunakan Encore.ts.

  2. Masa jalan berprestasi tinggi, dengan gelung acara berbilang benang dan tak segerak yang ditulis dalam Rust (menggunakan Tokio dan Hyper).

Encore Runtime mengendalikan semua I/O seperti menerima dan memproses permintaan HTTP yang masuk. Ini berjalan sebagai gelung acara bebas sepenuhnya yang menggunakan seberapa banyak urutan yang disokong oleh perkakasan asas.

Apabila permintaan telah diproses dan dinyahkod sepenuhnya, ia akan diserahkan kepada gelung peristiwa Node.js, dan kemudian mengambil respons daripada pengendali API dan menulisnya kembali kepada pelanggan.

(Sebelum anda menyebutnya: Ya, kami meletakkan gelung acara dalam gelung acara anda, supaya anda boleh gelung acara semasa anda gelung acara.)

Encore.ts — faster than ElysiaJS & Hono

2. Encore.ts pra-pengiraan skema permintaan

Encore.ts, seperti namanya, direka dari bawah untuk TypeScript. Tetapi anda sebenarnya tidak boleh menjalankan TypeScript: ia perlu dikompilasi terlebih dahulu kepada JavaScript, dengan melucutkan semua maklumat jenis. Ini bermakna keselamatan jenis masa jalan jauh lebih sukar untuk dicapai, yang menjadikannya sukar untuk melakukan perkara seperti mengesahkan permintaan masuk, yang membawa kepada penyelesaian seperti Zod menjadi popular untuk menentukan skema API pada masa jalan.

Encore.ts berfungsi secara berbeza. Dengan Encore, anda mentakrifkan API jenis selamat menggunakan jenis TypeScript asli:

import { api } from "encore.dev/api";

interface BlogPost {
    id:    number;
    title: string;
    body:  string;
    likes: number;
}

export const getBlogPost = api(
    { method: "GET", path: "/blog/:id", expose: true },
    async ({ id }: { id: number }) => Promise<blogpost> {
        // ...
    },
);
</blogpost>

Encore.ts kemudian menghuraikan kod sumber untuk memahami permintaan dan skema respons yang dijangkakan oleh setiap titik akhir API, termasuk perkara seperti pengepala HTTP, parameter pertanyaan dan sebagainya. Skema kemudiannya diproses, dioptimumkan dan disimpan sebagai fail Protobuf.

Apabila Encore Runtime dimulakan, ia membaca fail Protobuf ini dan pra-pengiraan penyahkod permintaan dan pengekod tindak balas, dioptimumkan untuk setiap titik akhir API, menggunakan definisi jenis tepat yang dijangkakan oleh setiap titik akhir API. Malah, Encore.ts juga mengendalikan pengesahan permintaan secara langsung dalam Rust, memastikan permintaan yang tidak sah tidak perlu menyentuh lapisan JS sekalipun, mengurangkan banyak serangan penafian perkhidmatan.

Pemahaman Encore tentang skema permintaan juga terbukti bermanfaat dari perspektif prestasi. Waktu jalan JavaScript seperti Deno dan Bun menggunakan seni bina yang serupa dengan masa jalan berasaskan Rust Encore (malah, Deno juga menggunakan Rust Tokio Hyper), tetapi kurang pemahaman Encore tentang skema permintaan. Akibatnya, mereka perlu menyerahkan permintaan HTTP yang tidak diproses kepada enjin JavaScript satu benang untuk dilaksanakan.

Encore.ts, on the other hand, handles much more of the request processing inside Rust, and only hands over the decoded request objects. By handling much more of the request life-cycle in multi-threaded Rust, the JavaScript event-loop is freed up to focus on executing application business logic instead of parsing HTTP requests, yielding an even greater performance boost.

3. Encore.ts integrates with infrastructure

Careful readers might have noticed a trend: the key to performance is to off-load as much work from the single-threaded JavaScript event-loop as possible.

We've already looked at how Encore.ts off-loads most of the request/response lifecycle to Rust. So what more is there to do?

Well, backend applications are like sandwiches. You have the crusty top-layer, where you handle incoming requests. In the center you have your delicious toppings (that is, your business logic, of course). At the bottom you have your crusty data access layer, where you query databases, call other API endpoints, and so on.

We can't do much about the business logic — we want to write that in TypeScript, after all! — but there's not much point in having all the data access operations hogging our JS event-loop. If we moved those to Rust we'd further free up the event loop to be able to focus on executing our application code.

So that's what we did.

With Encore.ts, you can declare infrastructure resources directly in your source code.

For example, to define a Pub/Sub topic:

import { Topic } from "encore.dev/pubsub";

interface UserSignupEvent {
    userID: string;
    email:  string;
}

export const UserSignups = new Topic<usersignupevent>("user-signups", {
    deliveryGuarantee: "at-least-once",
});

// To publish:
await UserSignups.publish({ userID: "123", email: "hello@example.com" });
</usersignupevent>

"So which Pub/Sub technology does it use?"
— All of them!

The Encore Rust runtime includes implementations for most common Pub/Sub technologies, including AWS SQS+SNS, GCP Pub/Sub, and NSQ, with more planned (Kafka, NATS, Azure Service Bus, etc.). You can specify the implementation on a per-resource basis in the runtime configuration when the application boots up, or let Encore's Cloud DevOps automation handle it for you.

Beyond Pub/Sub, Encore.ts includes infrastructure integrations for PostgreSQL databases, Secrets, Cron Jobs, and more.

All of these infrastructure integrations are implemented in the Encore.ts Rust Runtime.

This means that as soon as you call .publish(), the payload is handed over to Rust which takes care to publish the message, retrying if necessary, and so on. Same thing goes with database queries, subscribing to Pub/Sub messages, and more.

The end result is that with Encore.ts, virtually all non-business-logic is off-loaded from the JS event loop.

Encore.ts — faster than ElysiaJS & Hono

In essence, with Encore.ts you get a truly multi-threaded backend "for free", while still being able to write all your business logic in TypeScript.

Conclusion

Whether or not this performance is important depends on your use case. If you're building a tiny hobby project, it's largely academic. But if you're shipping a production backend to the cloud, it can have a pretty large impact.

Lower latency has a direct impact on user experience. To state the obvious: A faster backend means a snappier frontend, which means happier users.

Higher throughput means you can serve the same number of users with fewer servers, which directly corresponds to lower cloud bills. Or, conversely, you can serve more users with the same number of servers, ensuring you can scale further without encountering performance bottlenecks.

While we're biased, we think Encore offers a pretty excellent, best-of-all-worlds solution for building high-performance backends in TypeScript. It's fast, it's type-safe, and it's compatible with the entire Node.js ecosystem.

And it's all Open Source, so you can check out the code and contribute on GitHub.

Or just give it a try and let us know what you think!

以上是Encore.ts — 比 ElysiaJS 和 Hono 更快的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架:为现代网络开发提供动力JavaScript框架:为现代网络开发提供动力May 02, 2025 am 12:04 AM

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

JavaScript,C和浏览器之间的关系JavaScript,C和浏览器之间的关系May 01, 2025 am 12:06 AM

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境