do I incur a penality on compile time if I explicitly declare default behavior ?

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 21 13:23:04 UTC 2021


On 6/21/21 12:12 AM, someone wrote:
> I mean, coding as following:
> 
> ```d
> int intWhatever = 0; /// default being zero anyway
> 
> foreach (classComputer objComputer, objComputers) { ... } /// explicitly 
> declaring the type instead of letting the compiler to figure it out
> 
> struc Whatever {
> 
>     public doSomething() { ... } /// explicitly declaring scopes 
> matching the default ones
> 
> }
> 
> string[] strWhatever;
> if (strWhatever.length > cast(size_t) 1) { ... } /// explicitly casting 
> for proper types although not required to at all
> ```
> 
> ... and the likes; or, besides unnecessary typing, are there any cons 
> that I should be aware of while using DMD ?
> 

For sure there is a difference in what the compiler has to do.

But I think the check is likely trivial, and inconsequential as far as 
compiler runtimes. D is going to already figure out the types of 
expressions *with or without explicit types*. The extra step is when it 
has to check if it can convert from the detected type to the declared one.

I would be more concerned with possible conversions you didn't expect 
being silently performed by the compiler. e.g. if a type is alias this'd 
to a `string`, and you declare `string` as the foreach type, then it's 
going to run the alias this at runtime, even if that might be expensive.

This might happen even though you wrote the actual type at the time -- 
sometimes library code changes the type, and just uses alias this to 
allow original code to compile.

-Steve


More information about the Digitalmars-d-learn mailing list