foreach vs static foreach on compile time tuples

monkyyy crazymonkyyy at gmail.com
Tue Aug 26 18:48:47 UTC 2025


On Sunday, 24 August 2025 at 08:35:57 UTC, Per Nordlöw wrote:
> Which are the pros and cons of foreach vs static foreach on a 
> compile time tuple in D in terms of compiler performance and 
> resource usage? Does static foreach generate more ast 
> duplications?

Since enum foreach is being deleted and nore properly implimented 
(ugh that not why I report bugs; to remove features) I believe in 
practice both should be O(n) but there isnt a way to generate a 
alias foreach lazily, it will exist in memory so it must allocate 
O(n)

I would predict that alias foreach will be 2x slower until your 
ram is filled at a point 1/2 the size of static foreach(at which 
point a new curve gets introduced) which swap being worse then 
ram skyrockets, then shortly after static foreach joins in.

---

```d
#!opend -unittest -main -run app.d
bool isEvenImpl(int I)()=>! I%2;
enum cases=10000;
import std.range;
bool isEven(int i){
	switch(i){
		static foreach(I;0..cases){
		//foreach(I;enumlist!(iota(cases))){
			case I: return isEvenImpl!I;
		}
		default: assert(0);
}}
template Val(int V){
	enum Val=V;
}
alias seq(T...)=T;
template enumlist(alias R){
	alias enumlist=seq!();
	static foreach(e;R){
		enumlist=seq!(enumlist,Val!e);
}}
unittest{
	import std;
	alias A=enumlist!(iota(5));
	A.stringof.writeln;
}
unittest{
	import std;
	7.isEven.writeln;
}
```

> static foreach(I;0..cases){ //2.86s
> foreach(I;enumlist!(iota(cases))){ //7.30s

Not going to do more tests but I believe you should stick with 
static each when possible but im pretty sure they share bigO 
details


More information about the Digitalmars-d-learn mailing list