I’ve reformatted your post for clarity. Please learn to use code fences (```) when posting code.
You have declared $page within an if statement, so its scope is restricted to within the if statement. The same would be true if you declared the variable within a with or range construct.
You need to do something like this:
{{ $a := "" }}
{{ if .IsPage }}
{{ $a = "foo" }}
{{ end }}
When you build your site with the hugo command, the build time is affected by your template code. If you used 1000 if statements in a template, and you built a site with 1000 pages, that might add a few seconds to your build time.
But the speed at which your published pages are served to a browser would not be affected; Hugo is a static site generator.