In Javascript, is it expensive to use try-catch blocks even if an exception is never thrown?

阅读时长 3 分钟读完

Communitycprcrack提出了一个问题:In Javascript, is it expensive to use try-catch blocks even if an exception is never thrown?,或许与您遇到的问题类似。

回答者K48Esailija给出了该问题的处理方式:

Are you doing typical CRUD UI code? Use try catches, use loops that go to 10000 for no reason sprinkled in your code, hell, use angular/ember - you will not notice any performance issue.

If you are doing low level library, physics simulations, games, server-side etc then the never throwing try-catch block wouldn't normally matter at all but the problem is that V8 didn't support it in their optimizing compiler until version 6 of the engine, so the entire containing function that syntactically contains a try catch will not be optimized. You can easily work around this though, by creating a helper function like tryCatch:

-- -------------------- ---- -------
-------- ------------- -
    --- -
        ------ ------
    -
    -------- -
        ------------------- - --
        ------ ------------------
    -
-
----------------- - --- ------

--- ------ - -------------------------------------
--------- --- ------------------ -
    ----- -------- -----
    --- - - ---------
-
---- -
    -------- -- --- -------- -----
-

After V8 version 6 (shipped with Node 8.3 and latest Chrome), the performance of code inside try-catch is the same as that of normal code.

希望本文对你有帮助,欢迎支持JavaScript中文网

来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/28567

纠错
反馈