Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8101841
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T23:05:14+00:00 2026-06-05T23:05:14+00:00

Sometimes I have to check for some condition that doesn’t change inside a loop,

  • 0

Sometimes I have to check for some condition that doesn’t change inside a loop, this means that the test is evaluated in every iteration, but I think this isn’t the right way.

I thought since the condition doesn’t change inside the loop I should only test it only once outside the loop, but then I will have to "repeat myself" and possibly write the same loop more than once. Here’s a code showing what I mean:

#!/usr/bin/python

x = True      #this won't be modified  inside the loop
n = 10000000

def inside():
    for a in xrange(n):
        if x:    #test is evaluated n times
            pass
        else:
            pass
    
def outside():
    if x:        #test is evaluated only once
        for a in xrange(n):  
            pass
    else:
        for a in xrange(n):
            pass

if __name__ == '__main__':
    outside()
    inside()

Running cProfile on the previous code gave the following output:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.542    0.542    0.542    0.542 testloop.py:5(inside)
        1    0.261    0.261    0.261    0.261 testloop.py:12(outside)
        1    0.000    0.000    0.803    0.803 testloop.py:3(<module>)

This shows that obviously, testing once outside the loop gives better performance, but I had to write the same loop twice (maybe more if there were some elifs).

I know that this performance won’t matter in most cases, but I need to know what’s the best way to write this kind of code. For example is there a way to tell python to only evaluate the test once ?

Any help is appreciated, thanks.

EDIT:

Actually after making some tests, I’m now convinced that the difference in performance is mainly affected by other code performed within the loops, not by the evaluation of tests. So for now I’m sticking with the first form, which is more readable, and better for debugging later.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T23:05:16+00:00Added an answer on June 5, 2026 at 11:05 pm

    First, a major component of the performance difference between your examples is the time it takes to lookup a global. If we capture it into a local variable:

    def inside_local():
        local_x = x
        for a in xrange(n):
            if local_x:
                pass
            else:
                pass
    
    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.258    0.258    0.258    0.258 testloop.py:13(outside)
        1    0.314    0.314    0.314    0.314 testloop.py:21(inside_local)
        1    0.421    0.421    0.421    0.421 testloop.py:6(inside)
    

    most of the performance difference disappears.

    In general whenever you have common code you should try to encapsulate it. If the branches of the if have nothing in common apart from the loop then try to encapsulate the loop iterator e.g. into a generator.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application that needs to check a website feed every second. Sometimes
I have a webapp that needs to sometimes download some bytes from a url
I have some java components that sometimes die and the only way I know
I have an Excel file that contains some values. I need to check if
I have some H3 elements that sometimes are followed by a P element. I
I have a form that sometimes gets linked to with some query string parameters.
I see on sites that they sometimes have a statistic showing how many views
Sometimes I have to write code that alternates between doing things and checking for
I have noticed that sometimes people have to use multiple versions of jQuery in
Step 1) I check that i can acess server: (because i have offline handling

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.