4 ms·
I have read the examples, and it seems like this cannot be used for aggressive hoisting of conditionals by writing "if (comptime foo)", resulting in the the bod
by anonymoushn 1y ago
I have read the examples, and it seems like this cannot be used for aggressive hoisting of conditionals by writing "if (comptime foo)", resulting in the the body of the if statement being executed unconditionally or omitted. So it cannot replace my current use of C preprocessor macros in Javascript, though Zig's actual comptime feature could.
- trgwii 1y agoYes it can, the comptime expression inside the if would turn into a `true` or `false` literal, but you would need a separate build tool to optimize away the if. That's partly why comptime.ts outputs TypeScript iirc. I believe both Vite and Bun bundler would apply the optimization to eliminate constant conditionals when you use comptime.ts as a plugin.
- anonymoushn 1y agoI don't have any experience running the Vite or Bun bundlers or the typescript compiler on the client, but I think these are not really supported use cases.
- alpinisme 1y agoWhy are you trying to run this on the client? At the time you’re shipping code you’re already past the point of comptime. It’d be wasteful to do anything client side beyond execute the code you sent.
- anonymoushn 1y agothe alternative is to send exponentially many copies of the code to the client, i guess
- MrJohz 1y agoThis can be used as part of that step (i.e. converting `foo()` into `true` or `false`), but I think the expectation is that you'll have another step in the build process that automatically strips away `if(false)...` statements and inlines `if(true)` ones. Almost any minifier will automatically do this, for example, and most can be configured so that they only do constant folding/dead code elimination, so the result will be a file that looks like the one you've written, but with these comptime conditions removed/inlined. Obviously with C preprocessor macros, you've got one tool that evaluates the condition and removes the dead code, but with comptime you have more flexibility and your conditions are all written in Javascript rather than a mix of JS and preprocessor macros.
- anonymoushn 1y agoI think it is a bit more troublesome to ship a this comptime implementation and a minifier to the client so the specialization may be performed there than it is to ship just a c preprocessor implementation.
- MrJohz 1y agoThat'll depend a lot on the context and the client, I imagine. Comptime and the minifier can be distributed in a fairly standard way as part of an NPM package's dependencies, so if you're shipping to a system that can handle NPM, then comptime doesn't really add much. But if the client doesn't have a JS runtime installed or can't easily access the NPM ecosystem, then I can imagine shipping the C preprocessor could well be easier than juggling two different tools.